通过动态加载表单内容,要求检测加载之后有没有变更过,可以通过defaultValue或者defaultSelected、defaultChecked属性来完成
首先,加载完成后设置默认值为当前状态的值:
//设置当前值为表单默认值 function setDefault(element) { if (typeof (element) == "string") { element = document.getElementById(element); if (!element) { return null; } } var type = element.type; if (type == "checkbox" || type == "radio") { element.defaultChecked = element.checked; } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { element.defaultValue = element.value; } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j < element.options.length; j++) { element.options[j].defaultSelected = element.options[j].selected; } } var childs = element.childNodes; for (var i = 0; i < childs.length; i++) { setDefault(childs[i]); } }
检测代码:
//判断表单是否改变过 function formIsDirty(form) { if (typeof (form) == "string") { form = document.getElementById(form); if (!form) { return null;} } for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j < element.options.length; j++) { if (element.options[j].selected != element.options[j].defaultSelected) { return true; } } } } return false; }