我想获得tr
在其类"foo"中的索引,但我希望它只计算表中该类的元素并不是每一个"食物"在身体里。所以我想让i得到这个:
<表类>
表
表
表
tbody><<tr>0 0 0 11 1 22 2 表类>
在当前表中所有.foo
的集合上调用.index()
,将当前行作为参数传递。返回集合内的索引。
document.querySelectorAll("td").forEach(i => {
let row = $(i).closest("tr");
$(i).text(row.closest("table").find(".foo").index(row));
})
table {
border-collapse: collapse;
float: left;
margin: 2px;
}
th,
td {
border: thin solid lightgrey;
height: 15px;
padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
</body>
</html>
我会使用jquery。我已经对代码进行了评论,它应该是可以理解的!:)
$(function(){
$('table').each(function(){ // find all table
if($(this).find('.foo').length > 0){ // check if the foo class is present
var counter = 0;
$(this).find('.foo td').each(function(){ // Count and number cells
$(this).text(counter);
counter++;
})
}
})
})
table {
border-collapse: collapse;
float: left;
margin: 2px;
}
th,
td {
border: thin solid lightgrey;
height: 15px;
padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
<table>
<tr>
<th>TABLE</th>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
<tr class="foo">
<td></td>
</tr>
</table>
</body>
</html>