I want to write Jquery code in master file, so that if there if user changes page and there is any unsaved changes user should get alert. I got one answer from this: link

However in most solution I will have to write code on all pages. I want it to write only at one place so that everybody dont have to worry to write it in their modules. My code is like:

<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>

但每次我在文本框中进行更改.change()事件未触发.

代码中可能有什么错误?

编辑: 我将.change()更改为.click,它就会触发.我使用的是jQuery 1.4.1..是因为jQuery版本导致change()不起作用吗?

推荐答案

This is what i am using, Put all this code in a separate JS file and load it in your header file so you will not need to copy this again and again:

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;

EDIT for $ not found:

此错误只能由以下三种原因之一引起:

  1. 您的JavaScript文件未正确加载到页面中
  2. 你有一个拙劣的jQuery版本.这可能是因为有人编辑了核心文件,或者插件可能已经覆盖了核心文件$
  3. 在页面完全加载之前,也就是在jQuery完全加载之前,您已经运行了JavaScript.

Make sure all JS code is being placed in this:

$(document).ready(function () {
  //place above code here
});

Edit for a Save/Send/Submit Button Exception

$('#save').click(function() {
    unsaved = false;
});

Edit to work with dynamic inputs

// 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;
});

Add the above code in your alert_unsaved_changes.js file.

Hope this helps.

Jquery相关问答推荐

如何定位 prism.js 脚本中包含的代码?

如何使用 jquery 获取屏幕的高度

foreach for JSON 数组,语法

数据表警告(表 id = 'example'):无法重新初始化数据表

在 Javascript 中,字典理解或 Object `map`

如何通过 Select 插件使用 jQuery 验证?

如何在 jQuery 中修改序列化的表单数据?

在完成前一个请求之前中止新的 AJAX 请求

使用带有 HTML 表格的 jQuery UI 可排序

jquery变量语法

如何使用jQuery在弹出窗口中预览输入类型=文件中的选定图像?

使用 MVC、C# 和 jQuery 导出为 CSV

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

触发下拉更改事件

如何在 JQuery 中 Select 除单击元素之外的所有类?

jQuery 追加淡入

jQuery slideUp().remove() 在删除发生之前似乎没有显示 slideUp 动画

单击时平滑滚动到特定的 div

如何确定滚动高度?

如何获取 jQuery 下拉值 onchange 事件