JavaScript onload和onunload [英] Javascript onload and onunload
问题描述
考虑下面的HTML代码段,其中包含一些使用提示符
和 unload
的javascript。 提示符()
方法可以正常工作,但在重新加载或离开页面时,我希望提醒 Goodbye,user 等内容。
Consider the following HTML snippet containing some javascript utilizing prompt
and unload
. The prompt()
method works fine but I want alerting something like Goodbye, user when reloading or leaving the page. Any help is greatly appreciated.
<body onload="promptName()" >
<script type="text/javascript">
function promptName()
{
var userName = prompt("What's your name ?", "")
return userName;
}
function goodBye()
{
alert("Goodbye, " + promptName() + "!");
}
window.onunload = goodBye();
</script>
</body>
推荐答案
您应该这样写:
window.onunload = goodBye;
另外,您可能会考虑在某些浏览器中使用onbeforeunload事件:
Also, you might consider using the onbeforeunload event in some browsers:
window.onbeforeunload = goodBye;
当您编写 window.onunload = goodBye();
将任何从 goodBye
返回的处理程序分配给 unload
事件。由于没有返回,所以不会有事件处理程序。您需要引用该函数: window.onunload = goodBye;
When you write window.onunload = goodBye();
you assign whatever handler that is returned from goodBye
to the unload
event. Since nothing is returned, there will be no event handler. You need to reference the function instead: window.onunload = goodBye;
这篇关于JavaScript onload和onunload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!