我正在修改此great post以对表中每列的值求和。我之所以使用它是因为该表可以是无限的行和列。
在这个mod中,我需要获取文本输入的值而不是单元格文本。我更改了sumOfColumns()函数的第二行,以包含查找find("input:nth-child(" + columnIndex + ")")
以获取所有表格行的输入而不是children("td:nth-child(" + columnIndex + ")")
。然而,它没有找到它们。我虽然find()得到了所有孩子,无论深度如何?
function sumOfColumns(table, columnIndex) {
var tot = 0;
table.find("tr").find("input:nth-child(" + columnIndex + ")")
.each(function() {
$this = $(this);
console.log($this);
if (!$this.hasClass("sum")) {
tot += parseInt($this.value());
}
});
return tot;
}
function do_sums() {
$("tr.sum").each(function(i, tr) {
$tr = $(tr);
//console.log($tr);
$tr.children().each(function(i, td) {
$td = $(td);
//console.log($td);
var table = $td.parent().parent().parent();
if ($td.hasClass("sum")) {
$td.html(sumOfColumns(table, i+1));
}
})
});
}
<table>
<tr>
<th>balance</th>
<td><input type="text" onchange="do_sums();"></td>
</tr>
<tr>
<th>gains</th>
<td><input type="text" onchange="do_sums();"></td>
</tr>
<tr>
<th>loses</th>
<td>-<input type="text" onchange="do_sums();"></td>
</tr>
<tr class="sum">
<th>Total</th>
<td class="sum">#</td>
</tr>
</table>
如何获得每列输入的值?
答案 0 :(得分:1)
问题是你正在寻找一个input
这是第n个孩子,但input
并不是它的父母的第n个孩子(td) )。
你真正想要找到的是input
td
里面的第{n}个孩子。
find("td:nth-child(" + columnIndex + ") input")