看看下面的例子
$(document).ready(function(){
$('#flights td').on('click', function(){
var colIndex = $(this).prevAll().length;
var rowIndex = $(this).parent('tr').prevAll().length + 1;
var cost = 0;
var sign = '';
for (var i = 0; i < rowIndex; i++)
{
var value = $('#flights tbody tr:eq(' + i.toString() + ') td:eq(' + (colIndex-1) + ')').html();
sign = value.substring(0,1);
cost += Number(value.substring(1));
}
$('#cost').text(sign + cost);
});
});
<table id="flights">
<thead>
<tr>
<th>Destination</th>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
<tbody>
<tr>
<th>One</th>
<td>$400</td>
<td>$450</td>
<td>$500</td>
</tr>
<tr>
<th>Two</th>
<td>$450</td>
<td>$500</td>
<td>$550</td>
</tr>
<tr>
<th>Three</th>
<td>$500</td>
<td>$550</td>
<td>$600</td>
</tr>
<tr>
<th>Four</th>
<td>$550</td>
<td>$600</td>
<td>$650</td>
</tr>
<tr>
<th>Five</th>
<td>$600</td>
<td>$650</td>
<td>$700</td>
</tr>
</tbody>
</table>
<label>Cost: </label> <label id="cost"></label>
解释:
1- $('#flights td') - 这是一个 jquery 选择器,用于获取名为“#flights”的表中的所有 td(s) ---- 你可以找到更多关于 jquery 选择器Here
2- .on('click', function(){}) - 这里我将一个事件处理函数附加到一个特定事件,即点击 ---- 你可以找到更多关于 .on() @ 987654322@
3- var colIndex = $(this).prevAll().length; - 这里我得到 CLICKED td 的列索引 ---- 你可以找到更多关于 .prevAll() Here
4- var rowIndex = $(this).parent('tr').prevAll().length + 1; - 这里我得到了 CLICKED td 的行索引----你可以找到更多关于 .parent() Here
5- for (var i = 0; i Here
6- var value = $('#flights tbody tr:eq(' + i.toString() + ') td:eq(' + (colIndex-1) + ')').html(); - 在这里,我根据被点击的 td 的静态列索引和循环内的行索引(即 i)来获取 td 内的值。 ---- 你可以找到更多关于 .html() Here
7- value.substring(0,1); - 我刚刚得到的标志可能会有所不同($、€)
这样我就可以在成本标签中连接它。 ---- 你可以找到更多关于 .substring() Here
8- 成本 += 数字(value.substring(1)); - 在这里,我获取每个 td 的值并剥离符号并将其转换为数字并将其添加到将填充在成本标签中的总成本中。
9- $('#cost').text(sign + cost); - 这里只是在成本标签中填充总成本并将符号连接到它。
您可以通过Here了解更多关于jquery的信息,这是一个很好的学习起点。