我已经编写了一个小型jQuery插件,可以在页面上查找表单输入的任何更改,并在用户离开页面时提醒用户不保存。
该插件如下所示:
(function ( $ ) {
$.extend({
unsaved: function() {
var unsaved = false;
$("form").find("input").on("change", function() {
unsaved = true;
});
$("form").on("submit", function() {
unsaved = false;
});
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;
}
});
}(jQuery));
我称之为:
// Look out for unsaved data
$.unsaved();
但是,我现在正在使用Ajax添加/删除一些数据,之后我想手动将unsaved
标记为true,以便用户在没有保存的情况下尝试离开页面时会收到警报。
我想我想做的事情就像是
// Call the plugin as normal
var unsaved = $.unsaved();
// Do some stuff with ajax here
// ...
// Manually mark the page as unsaved
unsaved.markAsUnsaved();
我尝试过以各种不同的方式在我的插件中创建markAsUnsaved()
函数,但无法让它工作。
答案 0 :(得分:0)
您必须返回markAsUnread
功能:
(function ( $ ) {
$.extend({
unsaved: function() {
var self = this;
self.isUnsaved = false;
$("form").find("input").on("change", function() {
self.isUnsaved = true;
});
$("form").on("submit", function() {
self.isUnsaved = false;
});
function unloadPage(){
if (self.isUnsaved){
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;
return {
markAsUnsaved: function() {
self.isUnsaved = true;
};
};
}
});
}(jQuery));
我们使用self
作为unsaved
插件类的参考,同时将unsaved
布尔变量重命名为与插件名称不同。然后插件返回一个包含markAsUnread函数的对象。