use*_*942 64 javascript jquery
我想在主文件中编写Jquery代码,这样如果用户更改页面并且有任何未保存的更改,则用户应该获得警报.我从这里得到了一个答案:链接
但是在大多数解决方案中,我将不得不在所有页面上编写代码.我希望它只在一个地方写,这样每个人都不必担心在模块中写它.我的代码是这样的:
<script type="text/javascript">
var isChange;
$(document).ready(function () {
$("input[type='text']").change(function () {
isChange = true;
})
});
$(window).unload(function () {
if (isChange) {
alert('Handler for .unload() called.');
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
但每次我在文本框中进行更改.change()事件都没有触发.
代码中有什么问题?
编辑:我将.change()更改为.click并将其触发.我正在使用jquery 1.4.1 ..是因为jquery版本,change()不起作用?
Alp*_*ale 102
这就是我正在使用的,将所有这些代码放在一个单独的JS文件中并将其加载到头文件中,这样您就不需要一次又一次地复制它:
var unsaved = false;
$(":input").change(function(){ //triggers change in all input fields including text type
unsaved = true;
});
function unloadPage(){
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
window.onbeforeunload = unloadPage;
Run Code Online (Sandbox Code Playgroud)
未找到$编辑:
此错误只能由以下三种情况之一引起:
- 您的JavaScript文件未正确加载到您的页面中
- 你有一个拙劣的jQuery版本.这可能是因为有人编辑了核心文件,或者插件可能覆盖了$变量.
- 您在页面完全加载之前运行JavaScript,因此,在jQuery完全加载之前.
确保所有JS代码都放在这里:
$(document).ready(function () {
//place above code here
});
Run Code Online (Sandbox Code Playgroud)
编辑保存/发送/提交按钮例外
$('#save').click(function() {
unsaved = false;
});
Run Code Online (Sandbox Code Playgroud)
编辑以使用动态输入
// Another way to bind the event
$(window).bind('beforeunload', function() {
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
});
// Monitor dynamic inputs
$(document).on('change', ':input', function(){ //triggers change in all input fields including text type
unsaved = true;
});
Run Code Online (Sandbox Code Playgroud)
在alert_unsaved_changes.js文件中添加以上代码.
希望这可以帮助.
fab*_*hel 12
使用表单序列化的版本:
当dom准备就绪时执行此代码:
// Store form state at page load
var initial_form_state = $('#myform').serialize();
// Store form state after form submit
$('#myform').submit(function(){
initial_form_state = $('#myform').serialize();
});
// Check form changes before leaving the page and warn user if needed
$(window).bind('beforeunload', function(e) {
var form_state = $('#myform').serialize();
if(initial_form_state != form_state){
var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
e.returnValue = message; // Cross-browser compatibility (src: MDN)
return message;
}
});
Run Code Online (Sandbox Code Playgroud)
如果用户更改字段然后手动回滚,则不会显示警告