问题描述
在使用window.location.assign加载页面后,是否可以调用javascript函数?我有这个代码。
< script language =javascripttype =text / javascript>
函数Loadspirit(){
window.location.assign(spirituality.php);
ReadEnglish();
}
< / script>
我加载页面然后调用ReadEnglish(),这是一个在spirituality.php中定义的函数。该功能不会执行。
只要您指定一个新的window.location,浏览器就会启动在当前浏览器窗口中加载新页面。这将停止在此窗口中执行所有JavaScript并开始加载新页面。只有在新页面中的JavaScript将从这一点开始运行。如果你在加载新页面后想要一个函数,你将不得不把这些代码放到新页面中。如果想让函数始终在新页面中运行,只需在新页面中设置代码,以便在页面加载时始终运行该函数。
如果您只希望在新页面中运行新函数,并从此特定上下文中调用该函数,那么您需要将一些信息传递到新页面和代码在新页面中需要查找该信息以决定是否运行ReadEnglish()函数。您可以将信息传递到新页面的典型方式是:
- 查询URL中的参数(URL之后的项目
- 在cookie中设置的信息
- 新页面已知的其他窗口/框架中的Javascript变量和
如果这不是一个持久性设置,通常会使用查询参数,而是偶尔执行此选项。特殊时间。
如果这是一个更持久的设置,通常会使用Cookie,因为Cookie可以保留,直到您告诉它离开。
Is it possible to call a javascript function after loading a page with window.location.assign? I have this code.
<script language="javascript" type="text/javascript">
function Loadspirit(){
window.location.assign("spirituality.php");
ReadEnglish();
}
</script>
I load the page then call ReadEnglish(), a function defined in spirituality.php. The function doesn't execute. What would be the way to make the function execute?
As soon as you assign a new window.location, the browser starts loading a new page in the current browser window. That stops execution of all javascript in this window and starts loading the new page. Only javascript in the new page will run from that point on. If you want a function after that new page is loaded, you will have to put that code in the new page. If want that function to run in the new page all the time, you can just set the code in that new page to always run that function when the page is loaded.
If you only want that new function to run in the new page when it's called from this particular context, then you need to pass some information to the new page and the code in the new page needs to look for that information to decide whether to run the ReadEnglish() function or not. The typical ways that you can pass information to the new page are
- Query parameters in the URL (items in the URL after the ? mark like "?run=English").
- Information set in a cookie
- Javascript variables in other windows/frames that are known to the new page and on the same origin.
Query parameters are often used if this is not a persistent setting, but rather an occasional execution of this option this particular time.
Cookies are often used if this is a more persistent setting because the cookie can persist until you tell it to go away.
这篇关于在使用window.location.assign加载页面后调用JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!