当前位置: 代码迷 >> Web前端 >> 关于jquery form plugin的1点改进
  详细解决方案

关于jquery form plugin的1点改进

热度:91   发布时间:2012-11-07 09:56:10.0
关于jquery form plugin的一点改进

form插件中的formToArray 的方法,原来处理方式var els = (semantic ? form.getElementsByTagName('*') : form.elements),导致自身没有子元素的可输入或可选的html标签不能获取到对应的key/value值.

经过修改后,例如

$("input").formToArray(false)才可获取得所有的input的key/value值。

?

附:

$.fn.formToArray = function(semantic) {
??? var a = [];
??? if (this.length == 0) return a;
??? var form = this[0];

?? //update by zhengcaihai 增加没有子元素的情况
? var els = (semantic ? form.getElementsByTagName('*') : form.elements)||this?

?? if (!els) return a;
??? for(var i=0, max=els.length; i < max; i++) {
??????? var el = els[i];
??????? var n = el.name;
??????? if (!n) continue;
??????? if (semantic && form.clk && el.type == "image") {
??????????? // handle image inputs on the fly when semantic == true
??????????? if(!el.disabled && form.clk == el)
??????????????? a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
??????????? continue;
??????? }

??????? var v = $.fieldValue(el, true);
??????? if (v && v.constructor == Array) {
??????????? for(var j=0, jmax=v.length; j < jmax; j++)
??????????????? a.push({name: n, value: v[j]});
??????? }
??????? else if (v !== null && typeof v != 'undefined')
??????????? a.push({name: n, value: v});
??? }

??? if (!semantic && form.clk) {
??????? // input type=='image' are not found in elements array! handle them here
??????? var inputs = form.getElementsByTagName("input");
??????? for(var i=0, max=inputs.length; i < max; i++) {
??????????? var input = inputs[i];
??????????? var n = input.name;
??????????? if(n && !input.disabled && input.type == "image" && form.clk == input)
??????????????? a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
??????? }
??? }
??? return a;
};

  相关解决方案