Javascript 当条件变为真时,如何禁用onbeforeunload?

Javascript 当条件变为真时,如何禁用onbeforeunload?,javascript,jquery,Javascript,Jquery,我有一个测试页面,用户可以在指定的时间内回答它 对于时间限制,我使用了javascript倒计时。直到时间结束,用户才能关闭窗口 为此,我使用了onbeforeuloadwindow事件来防止窗口像这样关闭: <script language="JavaScript"> window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to

我有一个测试页面,用户可以在指定的时间内回答它

对于时间限制,我使用了javascript倒计时。直到时间结束,用户才能关闭窗口

为此,我使用了
onbeforeuload
window事件来防止窗口像这样关闭:

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

window.onbeforeunload=确认退出;
函数confirmExit(){
return“您试图离开此页面。是否确定?”;
}
另一方面,在倒计时中,我设置了一个
timeUp
函数,在完成时间后将用户重定向到结果页面

在这种情况下,由于在卸载之前触发上述
onbeforeunload
,重定向失败,并向用户显示上述消息


当条件变为真时,是否有任何方法可以禁用
onbeforeunload
事件?

使用beforeunload事件处理程序调用unbind

 $(window).unbind('beforeunload');
或者试试看

 window.onbeforeunload = null;`

如果
onbeforeuload
功能不返回任何信息,浏览器将不会显示任何消息

因为您说过您使用了计时器功能来检查是否应该向用户显示消息

var displayMessage = true;
setTimeout(function() {
    displayMessage = false;
}, 10000);

function confirmExit() {
    if (displayMessage) {
        return "You have attempted to leave this page. Are you sure?";
    }
}
window.onbeforeunload = confirmExit;
在上述代码中-10秒后,displayMessage的值将为false,如果用户在10秒后尝试刷新/退出页面,浏览器将不会显示该消息