Javascript onUnload方法的问题 [英] Problem with Javascript onUnload method

查看:93
本文介绍了Javascript onUnload方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求当用户点击浏览器的[X]按钮时,我应该给他们一条消息。

I have a requirement that when the user clicks on [X] button of the browser, I should give them a message.

我使用onUnload完成了这项任务JavaScript的方法。

I accomplished this task using the onUnload method of JavaScript.

现在,即使我刷新页面,也会出现相同的消息!

Now, if even I refresh the page, then also the same message appears!

为什么会如此以及如何克服?

Why this is so and how to overcome?

代码在这里

<!DOCTYPE HTML PUBLIC - // W3C // DTD HTML 4.0 Transitional // EN>
< HTML>
< HEAD>
< script language =javascript>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <script language = "javascript">

function message()

function Message()

{
警报(你想离开吗?);
}

{ alert("Are you sre you want to leave?"); }

< / script>
< / HEAD>

</script> </HEAD>

< BODY onUnload =Message();>
< / BODY>< / HTML>

<BODY onUnload="Message();"> </BODY></HTML>

请帮助

推荐答案

这是正确的行为:刷新页面涉及到卸载然后重新加载。

That's correct behavior: refreshing the page involves unloading it and then loading it again.

接近这样一个确认对话框的最佳方法是使用以下代码:

The best way to approach such a confirm dialog is with code like this:

<script language="javascript" type="text/javascript">
window.onbeforeunload = function() {
    return "You have unsaved changes.";
}
</script>

这是您在GMail上看到的机制,如果您尝试关闭页面时消息尚未保存或发送。尝试刷新页面时仍会触发,因此确保只有在未保存的工作时才返回错误字符串非常重要。

This is the mechanism you see, for example, on GMail if you try to close a page when your message hasn't been saved or sent yet. It will still fire when attempting to refresh the page, so it's important to ensure you only return an error string if there really is unsaved work.

请记住,有不保证 onUnload onBeforeUnload 会触发事件,因为无法保证您的访问者甚至会启用JavaScript,所以你除了对未保存的工作的友好提醒外,不应该使用它。

Please keep in mind that there's no guarantee the onUnload or onBeforeUnload events will fire, since there's no guarantee your visitor will even have enabled JavaScript, so you shouldn't use this for anything more than a friendly reminder about unsaved work.

这篇关于Javascript onUnload方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆