无法删除beforeunload事件

时间:2018-07-19 11:47:10

标签: javascript jquery html

我们正在使用以下代码来显示刷新,选项卡关闭事件时的默认弹出窗口

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
  if ($('#timeExpiredtxt').hasClass('hide') && $("#submittedAnsResponseText").hasClass("hide")) {
    var confirmationMessage = 'You are attempting an assessment. Are you sure you want to leave this assessment?';
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
  }
});

我想在运行时删除并取消绑定此事件。我尝试了以下代码,但是没有运气。

$(window).off("beforeunload"); 
$(window).off("onbeforeunload"); 
window.onbeforeunload = null;

$(window).unbind(“ beforeunload”);

1 个答案:

答案 0 :(得分:0)

必须更改事件绑定代码。

function closeIt() {
    if ($('#timeExpiredtxt').hasClass('hide') && $("#submittedAnsResponseText").hasClass("hide")) {
        return "Any string value here forces a dialog box to \n" +
             "appear before closing the window.";
    }
}
window.onbeforeunload = closeIt;

并取消绑定下面的代码

window.onbeforeunload = null;