我很难将jQuery onbeforeunload
事件与jQuery UI Modal消息结合起来。我希望在卸载之前使用onbeforeunload事件来检查表单是否已经提交,如果还没有提交,则询问用户是否希望保存更改。
1 1rst函数提供系统提示并正常工作,但很难自定义样式或按钮文本,需要用户多次单击。
第二个函数使用jQuery UI Dialog,但它目前正在触发一个函数,该函数在任何字段被更改时显示对话框,而不是当用户试图离开页面时。如何更正此函数,使其在用户单击以离开页面而不提交表单时触发?
我使用的是jQuery1.8.2和jquery 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;
}
发布于 2013-03-12 18:07:30
尝试将对话框的定义移到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;
}
}
https://stackoverflow.com/questions/15367920
复制相似问题