日期:2014-05-16 浏览次数:20394 次
function checkModify(f, old) // 检查表单元素的内容哪些被修改了,old封装了表单初始化的内容 {// 参数f是传入的表单对象或是表单元素封装成的数组 var formElements = f.elements; if (f == "[object HTMLFormElement]") formElements = f.elements; else formElements = f; var element = ""; var newResult = ""; for ( var i = 0 in formElements) { element = formElements[i]; newResult += getElementPro(element); } newResult = newResult.substr(0, newResult.lastIndexOf(",")); newResult = "[" + newResult + "]"; var o = eval(newResult); var _o = old; var s = null; var _s=[]; for (aa in o) { for (bb in _o) { if (o[aa].name == _o[bb].name) { if (o[aa].value != _o[bb].value) { //s = s + o[aa].name + "=" + o[aa].value + "&"; _s.push(o[aa].name); _s.push("="); _s.push(o[aa].value); _s.push("&"); } } } } if (_s.length ==0) { alert("您还未做任何修改!"); if (f == "[object HTMLFormElement]") return false; } s=_s.join(""); if (f == "[object HTMLFormElement]") { f.action = f.action + "?" + s; return true; } else return s; } function markFormElements(f) // 封装了表单元素初始化时的值,将json类型数据封装到数组里,返回数组对象 {// 参数f可以是表单对象,也可以是表单元素封装成的数组 var formElements = ""; if (f == "[object HTMLFormElement]") formElements = f.elements; else formElements = f; var element = ""; var result = ""; var _result=[]; var type = ""; for ( var i = 0; i < formElements.length; i++) { element = formElements[i]; _result.push(getElementPro(element)); if(i!=formElements.length-1) _result.push(","); //result += getElementPro(element); } result=_result.join(""); //result = result.substr(0, result.lastIndexOf(",")); result = "[" + result + "]"; return eval(result); } function getElementPro(element) // 将表单元素name属性和值封装成json类型数据 { var a = ""; var _a=[]; if (element.type == "text" || element.type == "password" || element.type == "select-one" || element.type == "textarea") { //a += "{\"name\":\"" + element.name + "\",\"value\":\"" + element.value // + "\"},"; _a.push("{\"name\":\""); _a.push(element.name); _a.push("\",\"value\":\""); _a.push(element.value); _a.push("\"}"); } a=_a.join(""); return a; } 带form的调用实例 <html><head><title>测试</title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> </head> <body> <form name="theForm" action="test.jsp"> <input type="text" value="hehe" name="hehe"/> <input type="text" value="haha" name="haha"/> <input type="submit" value="提交" /> </form> <script type="text/javascript"> var temp=markFormElements($("form")[0]); $("form").submit(function(){ var flag=checkModify($(this)[0],temp); if(flag) if(confirm("确定提交修改内容?")) return true; return false; }); </script> </body> </html>