用客户端脚本提示用户在离开编辑页面之前进行数据保存
下面的代码阐述了如何通过一个客户端脚本防止用户在一个编辑页面未经保存数据就擅自离开页面,从而使得数据丢失,这里的关键是启用了onbeforesubmit事件,该事件将会在onsubmit事件之前发生。
代码
/*使得Form增加变更提示功能*/
$.fn.enable_changed_form_confirm = function() {
var _f = this;
$(':text, :password, textarea', this).each(function() {
$(this).attr('_value', $(this).val());
});
$(':checkbox, :radio', this).each(function() {
var _v = this.checked ? 'on' : 'off';
$(this).attr('_value', _v);
});
$('select', this).each(function() {
$(this).attr('_value', this.options[this.selectedIndex].value);
});
$(this).submit(function() {
window.onbeforeunload = null;
});
window.onbeforeunload = function() {
if (is_form_changed(_f)) {
return "你将丢失所有未保存的数据";
}
}
}
/* 判断Form中的值是否发生了变化*/
function is_form_changed(f) {
var changed = false;
$(':text, textarea', f).each(function() {
var _v = $(this).attr('_value');
if (typeof (_v) == 'undefined') _v = '';
if (_v != $(this).val()) changed = true;
});
$(':checkbox, :radio', f).each(function() {
var _v = this.checked ? 'on' : 'off';
if (_v != $(this).attr('_value')) changed = true;
});
$('select', f).each(function() {
var _v = $(this).attr('_value');
if (typeof (_v) == 'undefined') _v = '';
if (_v != this.options[this.selectedIndex].value) changed = true;
});
return changed;
}
/* 调用 */
$(function() {
$(':form').enable_changed_form_confirm();
});
$.fn.enable_changed_form_confirm = function() {
var _f = this;
$(':text, :password, textarea', this).each(function() {
$(this).attr('_value', $(this).val());
});
$(':checkbox, :radio', this).each(function() {
var _v = this.checked ? 'on' : 'off';
$(this).attr('_value', _v);
});
$('select', this).each(function() {
$(this).attr('_value', this.options[this.selectedIndex].value);
});
$(this).submit(function() {
window.onbeforeunload = null;
});
window.onbeforeunload = function() {
if (is_form_changed(_f)) {
return "你将丢失所有未保存的数据";
}
}
}
/* 判断Form中的值是否发生了变化*/
function is_form_changed(f) {
var changed = false;
$(':text, textarea', f).each(function() {
var _v = $(this).attr('_value');
if (typeof (_v) == 'undefined') _v = '';
if (_v != $(this).val()) changed = true;
});
$(':checkbox, :radio', f).each(function() {
var _v = this.checked ? 'on' : 'off';
if (_v != $(this).attr('_value')) changed = true;
});
$('select', f).each(function() {
var _v = $(this).attr('_value');
if (typeof (_v) == 'undefined') _v = '';
if (_v != this.options[this.selectedIndex].value) changed = true;
});
return changed;
}
/* 调用 */
$(function() {
$(':form').enable_changed_form_confirm();
});

浙公网安备 33010602011771号