【问题标题】:Combining the jQuery onbeforeunload event with jQuery UI Modal Message将 jQuery onbeforeunload 事件与 jQuery UI 模态消息相结合
【发布时间】:2013-02-28 08:40:00
【问题描述】:

我在将 jQuery onbeforeunload 事件与 jQuery UI 模态消息结合时遇到问题。我想使用 jquery onbeforeunload 事件来检查表单是否已提交,如果尚未提交,则询问用户是否要保存更改。

第一个功能提供系统提示并正常工作,但很难自定义样式或按钮文本,并且需要用户多次点击。

第二个函数使用 jQuery UI 对话框小部件,但它当前触发的函数会在任何字段发生更改时显示对话框,而不是在用户尝试离开页面时显示对话框。如何更正此功能,以便在用户单击离开页面而不提交表单时触发它?

我正在使用 jquery-1.8.2 和 jquery-ui-1.9.1

<form name="form2" id="form2" method="post" action="form2-exec.php">        
    <!-- Form Elements -->
    <div id="dialog-confirm" style="display:none;">
        Would you like to save your changes?
    </div>
    <a href="form1.php">BACK</a>
    <a href="#"><input type="submit" value="SUBMIT" /></a>
</form>

原始函数

$(function () {
    // Set the unload message whenever any form elements are changed
    $('input', 'select').change(function () {
        setConfirmUnload(true);
    });
    // Turn off the unload message whenever a form get submitted properly.
    $('form').submit(function () {
        setConfirmUnload(false);
    });
});
function setConfirmUnload(on) {
    var message = "You have unsaved data. Are you sure to leave the page?";
    window.onbeforeunload = (on) ? function() { return message; } : null;
}

新的 setConfirmUnload(on) 函数 (不能正常工作)

function setConfirmUnload(on) {
  var message = $("#dialog-confirm").dialog({
        modal: true,
        buttons: {
            "Save": function () {
                $("#form2").submit();
                $(this).dialog("close");
            },
            "Continue": function () {
                $(this).dialog("close");
            }
        }
    });        
    window.onbeforeunload = (on) ? function () { return message; } : null;
}

【问题讨论】:

    标签: jquery jquery-ui-dialog onbeforeunload


    【解决方案1】:

    尝试将对话框的定义移动到 window.onbeforeunload 处理程序中,如下所示:

    function setConfirmUnload(on) { 
        var message;       
        if (on) {
            window.onbeforeunload = function() {
                message = $("#dialog-confirm").dialog({
                    modal: true,
                    buttons: {
                        "Save": function () {
                            $("#form2").submit();
                            $(this).dialog("close");
                        },
                        "Continue": function () {
                            $(this).dialog("close");
                        }
                    }
                 });
                 return message;
            };
        } else {
            window.onbeforeunload = null;
        }
    }
    

    【讨论】:

    • 这导致标准系统提示和对话框弹出:-(
    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多