如果您更改页面上的数据然后离开页面,以下代码将执行警告。我想要 - 除非用户按下保存按钮。
这是jquery代码:
$(document).ready(function() {
formmodified=0;
$('form *').change(function(){
formmodified=1;
});
window.onbeforeunload = confirmExit;
function confirmExit() {
if (formmodified == 1) {
return "New information not saved. Do you wish to leave the page?";
}
}
});
这是保存数据的按钮:
<input class="btn-primary" name="commit" type="submit" value="Save Material">
更新谢谢tymeJV !!!!!!!
如果其他人需要它,这有效:
$(document).ready(function() {
formmodified=0;
$('form *').change(function(){
formmodified=1;
});
window.onbeforeunload = confirmExit;
function confirmExit() {
if (formmodified == 1) {
return "New information not saved. Do you wish to leave the page?";
}
}
$("input[name='commit']").click(function() {
formmodified = 0;
});
});
根据您的保存按钮信息:
<input class="btn-primary" name="commit" type="submit" value="Save Material">
您可以设置formmodified
的值
$("input[name='commit']").click(function() {
formmodified = 0;
});
现在不应该触发最后的检查
$('#form').data('serialize',$('#form').serialize()); // On load save form current state
$(window).bind('beforeunload', function(e){
if($('#form').serialize()!=$('#form').data('serialize'))return true;
else e=null; // i.e; if form state change show box not.
});
您可以使用Google JQuery Form Serialize功能,这将收集所有表单输入并将其保存在数组中。我想这个解释就够了:)
这不是上述问题的准确答案,但是对于那些正在寻找问题解决方案的人来说“像我一样通知用户未保存的表单更改”,我想推荐jQuery插件AreYouSure。这个非常轻量级的插件处理所有的坚果和粗体,如恢复的表单更改,单击表单重置按钮,添加/删除表单域等,而无需任何进一步的摆弄。
在模糊之前,您的警告不会显示,这不是100%万无一失。更改以下行以使其气密:
$('form *').change(function () {
至
$('form *').on('change input', function () {
如果要在单击链接时阻止页面离开,可以绑定到beforeunload事件并传入e:
$(document).ready(function() {
var modified = false;
$(window).bind('beforeunload', function(e){
if (modified) {
$.confirm({
'title' : 'Did You Save Your Changes?',
'message' : 'It seems as if you have made changes but didn\'t click Save.\nAre you sure you want to leave the page?',
'buttons' : {
'OK' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. This can be omitted if you prefer.
}
})
}
e.preventDefault();
}
});
});
首先,如果用户对表单进行了任何更改,您需要获取输入的值。所以我想出了这个答案:
document.querySelector('.send').addEventListener("click", function(){
window.btn_clicked = true;
});
window.onbeforeunload = function(){
if(!window.btn_clicked){
var bla = $('#lot_t').val(); // getting the value of input
if(!bla == ''){ //checking if it is not null
return 'Are you sure to leave this page?';
}
}
};