在td -访问下一个单元格中单击

Onclick in td - access next cells

本文关键字:单元格 单击 下一个 访问 td      更新时间:2023-09-26

我正在使用一个表来显示项目,单元格[0]上的onclick事件应该输出(警告)来自单元格[1]和单元格[2]的数据。

我不确定用哪种方法可以访问它们。

这是我到目前为止的代码http://jsfiddle.net/5uua7eyx/3/

也许有一种方法可以使用我的变量输入

HTML

<table id="items">
    <tr>
        <td onclick="ClickPic(this)">Picture0</td>
        <td>Name0</td>
        <td>Price0</td>
    </tr>
        <tr>
        <td onclick="ClickPic(this)">Picture1</td>
        <td>Name1</td>
        <td>Price1</td>
    </tr>         
</table>

JS

function ClickPic(e) {
    "use strict";
    var input = e.target;
    alert("Clicked!");
}

谢谢

传递的是this,它代表被单击的元素,而不是事件对象。

您需要做的就是使用参数从.parentNode中获得兄弟.cells,然后使用elem.cellIndex来计算下一个索引:

function ClickPic(elem) {
    "use strict";
    var cells = elem.parentNode.cells;
    var currIdx = elem.cellIndex;
    alert(cells[currIdx + 1].textContent + " " + cells[currIdx + 2].textContent);
}
<table id="items">
    <tr>
        <td onclick="ClickPic(this)">Picture0</td>
        <td>Name0</td>
        <td>Price0</td>
    </tr>
        <tr>
        <td onclick="ClickPic(this)">Picture1</td>
        <td>Name1</td>
        <td>Price1</td>
    </tr>         
</table>
x

如果你知道索引号总是12,那么你可以缩短它。

    alert(cells[1].textContent + " " + cells[2].textContent);

你可以这样修改js函数

<script type="text/javascript">
                function ClickPic(e) {
                var s = '';
                $(e).siblings().each(function() {
                s = s + ',' + $(this).text()

});

                alert(s);

}