JavaScript + onunload事件 [英] JavaScript + onunload event

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

问题描述

我想触发onunload事件来执行一些清理操作,我有多个选项卡(导航栏)显示了指向不同网页的多个链接,我的问题是,即使在其他页面中,我的卸载功能也位于其他jsp的标记被触发.请帮助解决此问题,我希望在用户关闭该页面中的浏览器时调用卸载功能.

I want to fire onunload event to do some clean up operations, I have multiple tabs(Navbar) showing multiple links to different web pages,my problem is that even when I'm in some other page my unload function which is in tag of some other jsp is fired. Please help to resove this, I want unload function to be called when user closes browser in that page.

推荐答案

我不确定您如何使onunload事件起作用....使用onunload事件发现的问题是它被触发了页面卸载后.这意味着,由于页面已被卸载,因此无法再执行JavaScript.

I'm not sure how you got the onunload event to work....The problem I've found with using the onunload event is that it is fired after the page has been unloaded. This means that no more JavaScript can be executed because the page has been unloaded.

您应该研究使用onbeforeunload事件. 此事件有点独特,因为如果处理此事件的函数返回任何内容,则会显示一个弹出窗口,询问用户是否要继续操作.因此,在您的情况下,请确保您的函数不返回任何内容.关于onbeforeunload事件要注意的另一件事是,Opera目前不支持该事件(但是Safari,FireFox和Internet Explorer支持).

You should be looking into using the onbeforeunload event. This event is a little unique because if the function that handles this event returns anything a pop up is displayed asking the user if they would like to continue with the operation. So, in your case make sure that your function doesn't return anything. The other thing to note about the onbeforeunload event is that, at this time, Opera does not support it (Safari, FireFox, and Internet Explorer do though).

每次页面卸载时,都会执行onbeforeunload和onunload事件.如果页面上的控件将该页面提交给服务器代码,则该页面将被卸载并执行JavaScript.

Both the onbeforeunload and onunload events are executed every time the page is unloaded. If a control on your page submits the page to the server code, the page is unloaded and the JavaScript is executed.

如果您不希望页面上的控件将JavaScript提交到服务器时执行JavaScript,则必须实施一些检查以查看是否应执行您的代码.

If you don't want the JavaScript to be executed when a control on your page is submitting it to the server you have to implement something that checks to see whether or not your code should be executed.

这很简单,向页面添加一个JavaScript布尔值,并将此布尔值设置为true的函数.确保页面中回发到服务器代码的每个元素在提交页面之前将此布尔值都设置为true.在onbeforeunload事件中检查此布尔值,以查看是否应执行清理代码.

This is simple, add a JavaScript boolean to the page and a function that set's this boolean to true. Make sure that every element in your page that posts back to your server code sets this boolean to true before it submits the page. Check this boolean in your onbeforeunload event to see if your cleanup code should be executed.

希望这会有所帮助,

-Frinny

这篇关于JavaScript + onunload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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