日期:2014-05-16 浏览次数:20813 次
背景:
? ? 产品要求提供ajax交互的体验方式,然后一张页面有那么多的表单,每个表单还有那么多的字段,而且当前页面只能显示一个form(其他form隐藏)所有的form表单的修改,添加都是在当前的页面内完成。
? ?一个字段一个字段去找太麻烦了,就采用了这个jquery插件jquery form plugin(http://jquery.malsup.com/form/),很好用,不用一个字段一个字段的去找了(重复劳动,一团代码什么的最讨厌了。。),然而悲剧就此发生了。。。
? ?因为当前页面同时只能显示一个form,但如果用户修改了,但没有提交,这时候的业务需求就是,将当前的表单reset的前一次状态,似乎没什么问题,挺简单的,把隐藏的时候将当前的form RESET到“页面渲染”的时候的状态(所有的表单都是在请求当前页面后将所有的字段赋值,没有通过js来做)。问题就出在这里,表单reset后始终记录的是请求后初始化的值。
解决方法:
? ? ?既然reset()方法记录的是页面初始化的值,将这个值修改就行了,直接修改表单的value还是不可以的,不信的可以去试试,反正我是试过了,其实原理很简单,给value赋值其实就是在表单上填值。如果这个有用,reset还有什么用呢?
? ??终归有方法的,公司牛人告诉我可以通过javascript setAttibute来做,果断试一下,过然可以。通用代码如下:
?
//改变Select控件的值
function changeSelectValAttr(helement) {
var j = 0, options = helement.options, t, selVal;
selVal = helement.value;
for ( ; j< options.length; j++) {
if (selVal == options[j].value) {
options[j].setAttribute("selected", "selected");
} else {
options[j].removeAttribute("selected");
}
}
}
?
?
?
//改变checkbox控件的值
function changeCheckValAttr(helement) {
var checks = helement.checked;
if (checks) {
helement.setAttribute("checked", "checked");
}
else {
helement.removeAttribute("checked");
}
}
?
function changeCommonTextValAttr(helement) {
helement.setAttribute("value", helement.value);
}
?
function changeRadioValAttr(helement) {
if (helement.checked) {
helement.setAttribute("checked", "checked");
} else {
helement.removeAttribute("checked");
}
}
?
?
function resetElementValAttr(helement) {
var tagName = helement.tagName, tagType = helement.type;
if (tagName.toUpperCase() == "INPUT" && tagType == "text") {
changeCommonTextValAttr(helement);
}
else if (tagName.toUpperCase() == "SELECT") {
changeSelectValAttr(helement);
}
else if (tagName.toUpperCase() == "INPUT" && tagType == "checkbox") {
changeCheckValAttr(helement);
}
else if (tagName.toUpperCase() == "INPUT" && tagType == "radio") {
changeRadioValAttr(helement);
}
}
function resetFormAttrs(aform) {
$.map(aform[0].elements, resetElementValAttr);
}
?
结束...
这是一篇忽悠人的文章。。。因为在IE中是无效的。。 我也很悲剧的,换了种解决方法,稍后。。
?
?
?