表单中未保存更改的警报

我想在主文件中编写 Jquery 代码,这样,如果有用户更改页面,并且有任何未保存的更改,用户应该得到警报。 我从中得到了一个答案: < a href = “ https://stackoverflow. com/questions/155739/thinking-unsave-changes-using-javascript”> 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 ()事件都不会触发。

代码会出什么问题?

编辑: 我变了。更改()至。按一下,它就开火了。我使用的是 jquery 1.4.1。.是不是由于 jquery 版本的原因 change ()不起作用了?

96134 次浏览

Change 事件在用户模糊输入时触发,而不是在输入的每个字符上。

如果你需要它被调用的时候,有些事情被改变(即使焦点仍然是在那个输入字段) ,你必须依赖于 钥匙扣和一堆事件的组合,以保持跟踪粘贴/剪切只使用鼠标。

附言。 我希望你能意识到你检测变化的方法并不是最好的?如果用户输入一些文本,离开字段,然后恢复更改,脚本仍然会提醒他修改过的文本。

你应该注册事件,不仅输入,而且文本区域,如果你的意思是文本区与文本框。您可以为 isChange 使用 keyup,这样就不必等待用户从这个区域模糊化。

$("input[type='text'], textarea").keyup(function () {
isChange = true;
})

这是我正在使用的,把所有这些代码在一个单独的 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 完全加载之前运行 JavaScript。

确保所有的 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 _ unsave _ changes. js 文件中。

希望这个能帮上忙。

为什么不简单地将事件绑定到 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
});

这实际上只是@AlphaMen 回答的另一个版本,但在几个方面有所改进:

# 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

这在以下方面更好:

  • 恕我直言,这是咖啡本自动使它更好。 :)
  • 它完全基于事件冒泡,所以动态内容可以自动处理(@AlphaMen 的更新也有这个功能)。
  • 它只在 POST 表单上运行,因为 GET 表单没有我们通常希望避免丢失的数据(即 GET 表单往往是搜索框和过滤条件)。
  • 它不需要绑定到执行保存的特定按钮。无论何时提交表单,我们都假设提交是保存的。
  • 它是 涡轮连接兼容的。如果你不需要,只需删除两个 page:事件绑定。
  • 它的设计使您可以将其包含在您的 JS 的其余部分中,并且您的整个站点将受到保护。

使用窗体序列化的版本:

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

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

我使用 $('form').change等函数来设置脏位变量。不适合捕获所有的变化(如前面的答案) ,但捕获所有我感兴趣的,在我的应用程序。