如何让浏览器后退按钮触发输入的更改事件?
我正在尝试检测输入字段的更改,以警告用户表单上未保存的更改。我在字段上使用 onchange 事件来记录表单的更改。然后,如果需要保存,我将使用 beforeunload 窗口事件来阻止用户离开页面。问题是所有主要浏览器上的后退按钮确实让活动输入触发更改事件。我该如何解决这个问题?
以下是我正在使用的测试文件。我希望当用户编辑输入字段然后立即单击返回时触发警报。编辑文本然后单击正文将触发更改,但这还不够。
starteditor.html
<!doctype html>
<html>
<head>
</head>
<body>
<a href="editor.html">Click me</a>
</body>
</html>
editor.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").delegate("input", "change", function () { alert("I changed") });
});
</script>
</head>
<body>
Edit text then click the browsers back button.
<form>
<input type="text" />
</form>
</body>
</html>
I'm trying to detect changes to input fields to warn users of unsaved changes on a form. I'm using the onchange event on fields to record that the form changed. I'm then using the beforeunload window event to stop the user from leaving the page if a save is needed. The problem is that the back button on all major browsers does let the active input fire the change event. How do I get around this problem?
Below are the test files I'm using. I want the alert to fire when the user edits the input field and then immediately clicks back. Editing the text and then clicking on the body will trigger change but that along is not enough.
starteditor.html
<!doctype html>
<html>
<head>
</head>
<body>
<a href="editor.html">Click me</a>
</body>
</html>
editor.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").delegate("input", "change", function () { alert("I changed") });
});
</script>
</head>
<body>
Edit text then click the browsers back button.
<form>
<input type="text" />
</form>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的回答:你不知道。
后退按钮属于用户,不属于页面的范围。您将获得的最接近的是
window.unload
事件。但窗口不会知道用户是否关闭了窗口、点击后退按钮、点击 F5 重新加载页面、在 URL 输入字段中输入新 URL、打开书签或告诉浏览器关闭或任何其他操作。您可以通过其他方式关闭页面。此外,您无法取消unload
事件:提供该事件是为了让页面可以干净地关闭。来自 http://www.w3.org/TR 的规范/DOM-Level-2-Events/events.html,第 1.6.5 节(HTML 事件类型):
Short answer: you don't.
The back button belongs to the user and is outside the purvey of the page. The closest you'll get is the
window.unload
event. But the window won't know whether the user has closed the window, hit the back button, hit the F5 to refload the page, typed a new URL into the URL entry field, opened a bookmark or told the browser to shut down or any other way you might dismiss a page. Further, you can't cancel theunload
event: it's provided so that the page can cleanly shut down.From the spec at http://www.w3.org/TR/DOM-Level-2-Events/events.html, section 1.6.5 (HTML event types):