我已經有了它的輸入工作,現在我認爲這只是我沒有注意到的愚蠢的錯誤。如何獲取動態表格輸入進入數組?
我的劇本是這樣的:
<script type="text/javascript">
$(document).ready(function() {
$('#clicker').on('click', function (e) {
var tableToObj = function (table) {
var trs = table.rows,
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];
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].children[j].innerHTML);
} else {
keys.push(sel.find('option:selected').val()); //all select works perfectly
}
var input = $(trs[i].children[j]).find("input"); //here I'm trying to find the input. This is where it stops working
if (input.length == 0) {
keys.push(trs[i].children[j].innerHTML);
} else {
keys.push(trs[i].childen[j].innerHTML);
}
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) { //this works
var sel = $(trs[i].children[j]).find("select");
if (sel.length == 0) {
obj[keys[j]] = trs[i].children[j].innerHTML;
} else {
obj[keys[j]] = sel.find('option:selected').val();
}
var input = trs.getElementsByTagName("input"); //below does not work
if (input.length == 0) {
obj[keys[j]] = trs[i].children[j].innerHTML;
} else {
obj[keys[j]] = input.find('text').val();
}
/*
for (j < input.length; j++) {
data.push(input[j].id);
}
*/
}
ret.push(obj);
}
}
return ret;
};
document.getElementById('r').innerHTML = JSON.stringify(tableToObj(document.getElementById('myTable')));
});
});
這裏是不太相關的HTML(包括剛看到我從拉)
<table id="myTable">
<thead>
<tr>
<th>FirstColumn</th>
<th>SecondColumn</th>
<th>ThirdColumn</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
<td>1</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
<tr>
<td></td>
<td>
</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" />
</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
</tbody>
</table>
編輯:因爲我有TRS [我]在它的意思是
你用了很多'input's和'select's的,你有一個'form'作爲家長嗎?如果是的話,爲什麼你不使用默認的jqery序列化程序呢?像'$('myForm')。serialize()' –
這裏是什麼#clicker'元素? –
爲什麼不使用'.getElementsByTagName('td')',通過循環並使用'.children [0]'引用您的輸入,因爲它們都是您的各自父元素中的所有第一個元素(它們也恰好是td) ?然後,您可以使用子元素的'.tagName'來確定要提取數據的子程序。從那裏弄清楚如何使它工作,無論子元素在哪裏都是微不足道的。你可以簡單地做另一個'.getElementsByTagName('*')'並用'.tagName'上的switch語句循環。 –