【问题标题】:Check which button clicked on page leave prompt?检查页面离开提示点击了哪个按钮?
【发布时间】:2014-01-08 19:35:12
【问题描述】:

所以我有这段代码,我正在尝试找出如何检查用户在提示上单击了哪个按钮。如果他们点击留下,我想触发一个事件,如果他们离开,我想触发一个不同的事件。这可能吗?

    var submitted = false;

    $(document).ready(function () {

        window.onbeforeunload = function (e) {
            if (!submitted) {
                var message = "Are you sure you want to leave?", e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }

     $("form").submit(function() {
         submitted = true;
     });
    });

【问题讨论】:

  • 如果他们点击是,那么onunload 将会触发。如果他们不这样做,那么它就不会触发。
  • 没有。 onbeforeunload 提示不可编写脚本

标签: javascript jquery alert


【解决方案1】:

据我所知,实际上没有办法找到点击了哪个按钮(在onbeforeunload确认框的情况下)。

但我们可以通过以下方式实现所需的功能:

window.onbeforeunload = function (e) {
    if( $("table tbody.files tr.template-download.fade").length > 0 )
    {
        var message = "XYZ",
        e = e || window.event;
        // For IE and Firefox
        if (e) {
            e.returnValue = message;
        }
        // For Safari
        return message;
    }
} 

您可以编写代码来点击下面的“是”按钮:

    $( window ).unload(function() {     
            //--> Here 
});

【讨论】:

    【解决方案2】:

    为此使用Javascript“确认”:

    if(confirm("Are you sure you want to leave?"))
    {
       //True part
    }
    else
    {
       //False part
    }
    

    【讨论】:

    • 确认没有给出页面离开提示(不管它叫什么。我知道这在技术上不是一个典型的提示)。
    • 注意:如果用户点击“确定”,则输入“真部分”,如果“取消”,则输入假部分。
    • 如何触发此页面离开?简单地在 onbeforeunload() 中转储它是行不通的。
    • 你确定 onbeforeunload() 被调用了吗?
    • 你能在这段代码中自己测试一下吗?我运气不好
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多