从未保存的更改页面导航时警告用户 [英] Warn User When Navigating from Page with Unsaved Changes
问题描述
我正在创建一个ASP.NET网站,并且我想实现一种逻辑来警告用户,当他们离开已编辑的页面时.
I'm creating an ASP.NET website and I want to implement logic to warn the user when they are navigating away from a page they've edited.
我在网上发现了很多信息,尽管其中大多数似乎已经过时了.请注意,我还有很多关于jQuery的知识.
I found quite a bit of info on the web, although most of it seems quite outdated. Note that I still have a lot to learn about jQuery.
以下代码按预期显示消息.
The following code displays the message as expected.
window.onbeforeunload = function () {
return 'You have unsaved changes!';
}
但是,以下代码(仅当进行更改时才应与上面的代码相等)不起作用.永远不会显示警告.
However, the following code--which is supposed to be equal to the code above only when a change is made--does not work. No warning is ever displayed.
$('input').change(function () {
window.onbeforeunload = function () { return "Your changes have not been saved?" };
});
有人可以说为什么第二个片段不起作用吗?或者,也许您可以将我引向较新的参考文献.
Can someone say why the second snippet doesn't work? Or perhaps you can point me to a reference that is more recent.
推荐答案
执行代码时,您的输入元素可能不存在.尝试使用 .live
函数检测所有输入元素上的更改,或将代码包装在<一个href ="http://api.jquery.com/ready/" rel ="noreferrer"> $(document).ready()
处理程序.
Your input elements probably do not exist when the code is executed. Try using the .live
function to detect changes on all input elements, or wrap your code in a $(document).ready()
handler.
示例:
$('input').live("change", function () {
window.onbeforeunload = function () { return "Your changes have not been saved?" };
});
或
$(document).ready(function () {
$('input').change(function () {
window.onbeforeunload = function () { return "Your changes have not been saved?" };
});
});
这篇关于从未保存的更改页面导航时警告用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!