我这里有这段代码
<table>
<thead>
<th>Title One</th>
<th>Title Two</th>
<th>Title Three</th>
</thead>
<tbody>
<?php foreach ($foos as $foo): ?>
<tr>
<td id="x"><?php echo $foo->bar1; ?></td>
<td id="y"><?php echo $foo->bar2; ?></td>
<td id="z"><?php echo $foo->bar3; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">
$('#x').on('click', function(){
console.log($(this).html());
});
</script>
假设我有 10 行数据,我如何才能引用我单击的确切元素?例如第 5 行,jQuery 如何知道我已经单击了第 5 行?我不能去写<td id="x1">
, <td id="x2">
, <td id="x3">
, <td id="x4">
因为我可以有一千条记录。
任何帮助将不胜感激。
最佳答案
您可以使用 closest('tr')
查找最近的父 tr
元素,然后使用 index()
获取行号。试试这个:
$('td').click(function() {
var $tr = $(this).closest('tr');
var rowIndex = $tr.index();
});
另请注意,您应该从 PHP 循环中的 td
元素中删除 id
属性,否则您将重复它们,这是无效的,可能会导致 JS 或渲染问题。
关于javascript - 在 foreach 循环中遍历 HTML DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30081554/