我无法将 jQueryonbeforeunload
事件与 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;
}