javascript – beforeunload或onbeforeunload

我被困在这些我应该使用哪一个:beforeunload或onbeforeunload他们似乎在做非常相似的事情,但具有不同的浏览器兼容性.

一些上下文:

我有一张表格在页面加载时,我将表单序列化并保存在变量中.如果用户离开页面,我将该表单序列化并比较两者,以查看是否有任何更改.但是,如果表单被提交,则不应该触发该事件.

实施例1

我有这样工作的预期.我只是不明白两者之间的区别:

window.onbeforeunload = function(e) {
    if(strOnloadForm != strUnloadForm)
        return "You have unsaved changes.";
}

当您保存表单(绑定到.submit())时,此行停止触发

window.onbeforeunload = null;

示例2

window.addEventListener("beforeunload",function( event ) {
    if(strOnloadForm != strUnloadForm)
        event.returnValue = "You have unsaved changes.";
});

当您保存表单(绑定到.submit())时,此行停止触发

window.removeEventListener("beforeunload");

文件说明了什么

我已经阅读了onbeforeunloadbeforeunload的文档.
在它之前说

You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there.

这让我觉得我应该使用后者.不过removeEventHandler的文档说:

addEventListener() and removeEventListener() are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts,allowing use of addEventListener() and removeEventListener() in implementations which do not natively support it.

有人可以请大家谈谈这些请求的差异,最好使用一下吗?

解决方法

window.onbeforeunload = function(){/ ** /}将覆盖任何现有的处理程序,并将其替换为您自己的.

window.addEventListener(“beforeunload”,function(){/ ** /});将添加一个新的处理程序.

addEventListener是首选.在旧版浏览器中(即IE6也许是IE7)可以使用attachEvent.

你通常会看到如下代码

function addEvent(object,event_type,event_handler) {
    if (object.addEventListener) {
        object.addEventListener(event_type,event_handler,false);
    } else {
        object.attachEvent("on" + event_type,handler);
    }
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...