javascript - 在 foreach 循环中遍历 HTML DOM 元素

标签 javascript php jquery html ajax

我这里有这段代码

<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();
});

Example fiddle

另请注意,您应该从 PHP 循环中的 td 元素中删除 id 属性,否则您将重复它们,这是无效的,可能会导致 JS 或渲染问题。

关于javascript - 在 foreach 循环中遍历 HTML DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30081554/

相关文章:

javascript - 使用 highcharts api 和 mysql 显示饼图

javascript - 为什么我们在原型(prototype)继承中使用临时盒子?

javascript - 如何定位特定范围内的图像?

php - 如何避免多对多查询中的 "Using temporary"?

php - 在while循环中解析json数据

jquery - 使用 JQuery 在按钮上添加 onclick 操作

javascript - 如何在javascript中生成仅变暗的随机颜色?

javascript - 删除Javascript中Set中的数组元素

javascript - 使用 React Native 将多个数据添加到 Firebase 中特定 id 的对象

php - SQL 查询问题 - 每年的客户支出总和