我尝试过表单序列化,并在单击“取消”按钮时检查是否进行了任何其他更改。现在我需要,即使发生任何导航,弹出窗口也应该出现。
var global=$("#form").serialize();
function cancelfunction(){
if(global!=$("#form").serialize()))
{//popup triggers }}
感谢
最佳答案
您可以创建一个 bool 标志来指示是否有任何更改,并且在每次输入类型更改时将其触发为 true,而在保存时将其设置为 false。在页面卸载时检查其值。
通常你会实现这样的目标:
alert('you have unsaved data!');
但是,浏览器在 beforeunload
上阻止警报,因此您需要这样做:
return 'you have unsaved data!';
代码:
// Initializing, this will set an initial value of false to the flag changeNoSave.
var changeNoSave;
// on change event of eachinput type we need to check on, we set the flag to true
// as change without submit has happened.
$('.checkMe').on('change', function() {
changeNoSave = true;
});
$('#submitBtn').on('click', function(e) {
//e.preventDefault() just for demo, not part of the solution
e.preventDefault();
//we set our flag to false again, as change has happened but saved upon form submit
changeNoSave = false;
console.log('you can leave the page safely');
});
$(window).on('beforeunload', function() {
// on before unloading the page, we check ifchanges happend but not saved , or like
// if changeNoSave = true, we alert by the return line
if (changeNoSave) {
return 'you have unsaved data!';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<input type="text" class="checkMe">
<input type="text" class="checkMe">
<input type="checkbox" id="chkbx" class="checkMe">
<label for="chkbx">Test</label>
<select class="checkMe">
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
<button id="submitBtn">submit</button>
</form>
关于jquery - 如何设置发生任何更改时退出弹出窗口并尝试移动到其他页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34626473/