74

我想在主文件中编写 Jquery 代码,这样如果用户更改页面并且有任何未保存的更改,用户应该得到警报。我得到了一个答案:link

但是在大多数解决方案中,我必须在所有页面上编写代码。我希望它只写在一个地方,这样每个人都不必担心在他们的模块中编写它。我的代码是这样的:

<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() 不起作用吗?

4

7 回答 7

129

这就是我正在使用的,将所有这些代码放在一个单独的 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;

未找到 $ 编辑:

此错误只能由以下三种情况之一引起:

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

确保所有 JS 代码都放置在此:

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

编辑保存/发送/提交按钮异常

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

编辑以使用动态输入

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

在您的 alert_unsaved_changes.js 文件中添加上述代码。

希望这可以帮助。

于 2012-08-07T10:54:51.677 回答
22

使用形式序列化的版本:

执行此代码,当 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;
  }
});

如果用户更改字段然后手动回滚,则不会显示警告

于 2016-01-20T11:59:19.670 回答
2

一旦用户从输入中模糊而不是在输入的每个字符上都将触发change事件。

如果您需要在每次更改某些内容时调用它(即使焦点仍在该输入字段中),您将不得不依靠keyup和一堆事件的组合来跟踪仅使用鼠标进行的粘贴/剪切。

PS我希望你知道你检测变化的方法不是最好的?如果用户输入一些文本,离开该字段然后恢复更改,脚本仍会提醒他有关修改的文本。

于 2012-08-07T10:49:56.103 回答
2

如果您的意思是带有文本框的 textarea,您不仅应该为输入注册事件,还应该为 textareas 注册事件。您可以将 keyup 用于 isChange,这样您就不必等待用户从该区域模糊。

$("input[type='text'], textarea").keyup(function () {
    isChange = true;
})
于 2012-08-07T10:53:30.120 回答
1

为什么不简单地将事件绑定到change回调?

$(":input").change(function()
{
    $(window).unbind('unload').bind('unload',function()
    {
        alert('unsaved changes on the page');
    });
});

作为额外的奖励,您可以使用confirm并选择触发更改事件的最后一个元素:

$(":input").change(function()
{
    $(window).unbind('unload').bind('unload',(function(elem)
    {//elem holds reference to changed element
        return function(e)
        {//get the event object:
            e = e || window.event;
            if (confirm('unsaved changes on the page\nDo you wish to save them first?'))
            {
                elem.focus();//select element
                return false;//in jQuery this stops the event from completeing
            }
        }
    }($(this)));//passed elem here, I passed it as a jQ object, so elem.focus() works
    //pass it as <this>, then you'll have to do $(elem).focus(); or write pure JS
});

如果您有一些保存按钮,请确保取消绑定卸载事件,但:

$('#save').click(function()
{
    $(window).unbind('unload');
    //rest of your code here
});
于 2012-08-07T11:04:19.763 回答
1

这实际上只是@AlphaMale 答案的不同版本,但在几个方面有所改进:

# Message displayed to user. Depending on browser and if it is a turbolink,
# regular link or user-driven navigation this may or may not display.
msg = "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

# Default state
unsaved = false

# Mark the page as having unsaved content
$(document).on 'change', 'form[method=post]:not([data-remote]) :input', -> unsaved = true

# A new page was loaded via Turbolinks, reset state
$(document).on 'page:change', -> setTimeout (-> unsaved = false), 10

# The user submitted the form (to save) so no need to ask them.
$(document).on 'submit', 'form[method=post]', ->
  unsaved = false
  return

# Confirm with user if they try to go elsewhere
$(window).bind 'beforeunload', -> return msg if unsaved

# If page about to change via Turbolinks also confirm with user
$(document).on 'page:before-change', (event) ->
  event.preventDefault() if unsaved && !confirm msg

这在以下方面更好:

  • 恕我直言,它是咖啡脚本自动使它变得更好。:)
  • 它完全基于事件冒泡,因此会自动处理动态内容(@AlphaMale 的更新也有这个)。
  • 它只在 POST 表单上运行,因为 GET 表单没有我们通常希望避免丢失的数据(即 GET 表单往往是搜索框和过滤条件)。
  • 它不需要绑定到特定的按钮来执行保存。每当提交表单时,我们假定提交正在保存。
  • 它与Turbolinks兼容。如果您不需要,只需删除两个page:事件绑定。
  • 它的设计使您可以将其包含在您的 JS 的其余部分中,并且您的整个站点都将受到保护。
于 2015-09-16T19:43:34.540 回答
0

我使用$('form').changeetc. 函数来设置脏位变量。不适合捕获所有更改(根据以前的答案),但在我的应用程序中捕获了我感兴趣的所有内容。

于 2016-10-19T08:15:34.000 回答