离开页面时,检测表单元素是否被修改,然后给出提示.防止用户错失修改的机会,提高用户体验。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://www.chenfahui.cn/ziliao/js/jquery-1.4.1.min.js"></script>
<title>jquery离开页面提示</title>
</head>
<body>
<script type="text/javascript">
window.onbeforeunload = function(){
if(is_form_changed()){return "您的修改内容还没有保存,您确定离开吗?"; }
}
function is_form_changed(){
//检测页面是否有保存按钮
var property_save = jQuery("#save");
//检测到保存按钮,继续检测元素是否修改
if(property_save.length>0){
var is_changed = false;
jQuery("#property input, #property textarea, #property select").each(function(){
var _v = jQuery(this).attr('_value');
if(typeof(_v) == 'undefined')
_v = '';
if(_v != jQuery(this).val())
is_changed = true;
});
return is_changed;
}
return false;
}
jQuery(document).ready(function(){
jQuery("#property input, #property textarea, #property select").each(function(){
jQuery(this).attr('_value', jQuery(this).val());
});
});
</script>
</body>
</html>