海豚宝宝的代码生活

专注于.Net系统开发

导航

用客户端脚本提示用户在离开编辑页面之前进行数据保存

下面的代码阐述了如何通过一个客户端脚本防止用户在一个编辑页面未经保存数据就擅自离开页面,从而使得数据丢失,这里的关键是启用了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(); 
 });
 

 

posted on 2010-03-15 16:06  Bruse  阅读(302)  评论(0)    收藏  举报