我试图做mi自己的序列化函数(比如在jQuery中),我需要在数组中获取输入和选择以便序列化它。
问题在于方法"推"和" pop"在DOM元素数组中不存在(错误:" Undefined不是函数")。
HTML:
<form>
<table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td><label for="age">Age:</label></td>
<td><input type="number" id="age" name="age"/></td>
</tr>
<tr>
<td><label for="genre">Genre:</label></td>
<td><select name="genre" id="genre">
<option>Female</option>
<option>Male</option>
</select></td>
</tr>
</table>
</form>
使用Javascript:
HTMLFormElement.prototype.ownSerialize=function() {
var inputs = this.getElementsByTagName('input');
var selects = this.getElementsByTagName('select');
while(selects.length)inputs.push(selects.pop());//Breaks here
console.log(inputs);
var json = {};
for (var f=0; f<inputs.length; f++) {
json[inputs[f].id]=inputs[f].value;
}
console.log(json);
var str = "?";
for(f in json){
str+=f+"="+json[f]+"&"
}
str = str.slice(0,-1); //Delete de last "&"
console.log(str);
};
document.getElementsByTagName('form')[0].ownSerialize();
我怎样才能实现它? http://jsfiddle.net/mpecdv2t/
(希望我的英语是正确的)
答案 0 :(得分:2)
您可以使用Array.prototype.slice
方法将HTMLCollection(以及任何其他类似数组的集合)转换为本机数组:
var slice = Array.prototype.slice;
var inputs = slice.call(this.getElementsByTagName('input'));
var selects = slice.call(this.getElementsByTagName('select'));
之后inputs
和selects
是真正的javascript数组,DOM元素作为数组元素。