假设我有一张 table :
<table id="myTable">
<thead>
<th> Col1 </th>
<th> Col2 </th>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
<tr><td>1</td><td>2</td></tr>
</tbody>
</table>
我想在名为 Col2 的列中添加值,即 4。我不想按列的位置添加值,即 answered here ,因为列的位置是可变的。
最佳答案
var index = $('table th:contains(Col2)').index(), // get index of th
sum = 0;
$('table tbody tr').each(function() {
sum += parseInt( $.trim( $('td:eq('+ index +')', this).text() ), 10);
});
一点解释
$('td:eq('+ index +')', this).text()
获取对应td的文本$.trim( $('td:eq('+ index +')', this).text() )
从文本中删除空格parseInt( $.trim( $('td:eq('+ index +')', this).text() ), 10)
转换 integet< 的值/p>sum += parseInt( $.trim( $('td:eq('+ index +')', this).text() ), 10);
执行总和。
<强> DEMO
关于JQuery 添加给定列名的列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10929480/