我相当接近,但顺序完全错了。此时输出全部搞砸了,我似乎无法将所有行添加到数组中
$('#clicker')。on('点击',功能(e){
var tableToObj = function(table){
var trs = table.rows,
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj,ret = [];
// j + = 1;
for(; i< trl; i ++){
if(i == 0){
for(; j< trs [i] .children.length; j ++){
var sel = $(trs [i] .children [j])。find(" select");
if(sel.length == 0){
keys.push(TRS [I]。儿童[j]的.innerHTML);
} else {
keys.push(sel.val());
}
}
} else {
obj = {};
for(j = 0; j< trs [i] .children.length; j ++){
var sel = $(trs [i] .children [j])。find(" select");
if(sel.length == 0){
obj [keys [j]] = trs [i] .children [j] .innerHTML;
} else {
keys.push(sel.val());
}
}
ret.push(OBJ);
}
}
返回;
};
document.getElementById(' r')。innerHTML = JSON.stringify(tableToObj(document.getElementsByTagName(' table')[0]));
});
});
我正在使用的HTML如下:
<表>
< TR>< TD> FirstColumn< / TD>< TD> SecondColumn< / TD>< TD> ThirdColumn< / TD>< / TR>
< tr>< td>< select>< option value =" tr1"> tr1< / option>< option value =" tr2"> tr2< /选项><选项值=" tr3"> tr3< /选项><选项值=" tr4"> tr4< /选项>< / select>< / td>< td> 1< / td>< td>< select>< option value =" tr1"> tr1< / option>< option value =" tr2&# 34;> tr2< / option>< option value =" tr3"> tr3< / option>< / select>< / td>< / tr>
< tr>< td> tr3 row< / td>< td>< / td>< td>< select>< option value =" tr1"> tr1< / option&gt ;<选项值=" tr2"> tr2< /选项><选项值=" tr3"> tr3< /选项><选项值=" TR4"> TR4< /选项>< /选择>< / TD>< / TR>
< tr>< td> tr4 row< / td>< td>< / td>< td>< / td>< / tr>
< TR>< TD> 0℃; / TD>< TD→1< / TD>< TD> 0℃; / TD>< / TR>
< TR>< TD> 0℃; / TD>< TD→1< / TD>< TD> 0℃; / TD>< / TR>
< /表>
< button id =" clicker"> Button< / button>
< br />
结果:
< div id =" r">< / div>
这是我得到的输出:
[{" SecondColumn":" 1"},{" FirstColumn":" tr3 row"," SecondColumn": ""},{" FirstColumn":" tr4 row"," SecondColumn":"",&# 34; ThirdColumn":""},{" FirstColumn":" 0"" SecondColumn":" 1& #34;" ThirdColumn":" 0"},{" FirstColumn":" 0"" SecondColumn" :" 1"" ThirdColumn":" 0"}]
这在改变选择值时不会改变。我非常有信心问题是for循环中的var sel。
谢谢
1 个答案:
答案 0 :(得分:0)
我认为有两件事需要解决:
-
要获取select
代码的值,您应该将sel.val()
的两个实例更改为sel.find('option:selected').val()
。
-
要解决排序问题,您需要在行循环的其他部分更新keys.push(
到obj[keys[j]] =
(当i> 0时)
醇>
JSFiddle Example