简体   繁体   English

window.confirm在FireFox中不起作用

[英]window.confirm not working in FireFox

Background: The goal is to keep a user from going back a page using the backspace. 背景:目的是防止用户使用退格键返回页面。 I've created code to disable the the key, except for a few input fields. 我创建了禁用该键的代码,除了一些输入字段。 But if they do, in fact, want to go back, I'd like for the confirm dialog to ask them if they REALLY want to go back or not. 但实际上,如果他们确实想回去,我想在确认对话框中询问他们是否真的想回去。

Problem: The following code works in IE and Chrome, but not FF. 问题:以下代码在IE和Chrome中有效,但不适用于FF。 The confirm pops up but it still goes 'back' a page. 确认弹出,但仍会“返回”页面。 This doesn't happen in IE/Chrome as the confirm dialog waits for user input. IE / Chrome中不会发生这种情况,因为确认对话框会等待用户输入。

Code: 码:

<script type="text/javascript">

    $(document).unbind('keydown').bind('keydown', function (event) {
        var doPrevent = false;
        if (event.keyCode === 8) {
            var d = event.srcElement || event.target;
            if ((d.tagName.toUpperCase() === 'INPUT' && 
                 (
                     d.type.toUpperCase() === 'TEXT' ||
                     d.type.toUpperCase() === 'PASSWORD' || 
                     d.type.toUpperCase() === 'FILE' || 
                     d.type.toUpperCase() === 'SEARCH' || 
                     d.type.toUpperCase() === 'EMAIL' || 
                     d.type.toUpperCase() === 'NUMBER' || 
                     d.type.toUpperCase() === 'DATE' )
                 ) || 
                 d.tagName.toUpperCase() === 'TEXTAREA') {


  doPrevent = d.readOnly || d.disabled;
        }
        else {
            var r = window.confirm("Leaving the page can cause data to be lost.  Are you sure?");
            if (!r) {
                doPrevent = true;
            }  
        }
    }

    if (doPrevent) {
        event.preventDefault();
        //event.stopPropagation(); 
    }
});

</script>

This fixed it and worked in each browser (Safari too): 此问题已修复,并可以在每个浏览器(Safari也是如此)中使用:

   window.addEventListener("beforeunload", function (e) {

    var confirmationMessage = "Leaving the page can cause data to be lost.  Are you sure?";

    e.returnValue = confirmationMessage;     // Gecko and Trident
    return confirmationMessage;              // Gecko and WebKit

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM