我正在使用表格来显示项目,单元格 [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
如果您知道索引号将始终为 1
和 2
,那么您可以缩短它。
alert(cells[1].textContent + " " + cells[2].textContent);
关于javascript - 在 td 中单击 - 访问下一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278810/