我在表中的每一行中都有一个按钮,一个用于按钮上的处理程序:
<button onclick="handler1(event)">aa</button>
如何从 event 中确定一行的索引?
请注意," handler1"的签名无法更改,即只能传递一个参数"事件"。
function handler1(myEvent) {
// index of a row from myEvent???
}
如果处理程序在某些嵌套元素上,则使用.parentNode
越过event.currentTArget
,直到找到TR
。
function handler1(myEvent) {
var el = myEvent.currentTarget;
while (el && el.nodeName !== "TR") {
el = el.parentNode;
}
console.log(el && el.rowIndex);
}
<table>
<tr>
<td>
<button onclick="handler1(event)">CLICK ME</button>
</td>
</tr>
<tr>
<td>
<button onclick="handler1(event)">CLICK ME</button>
</td>
</tr>
<tr>
<td>
<button onclick="handler1(event)">CLICK ME</button>
</td>
</tr>
</table>
如果您的 <td>
中的按钮喜欢:
<table>
<tr><td><button onclick="handler1(event)">click</button></td></tr>
<tr><td><button onclick="handler1(event)">click</button></td></tr>
</table>
以下应有作用:
function handler1(event) {
var rowIndex = event.currentTarget.parentNode.parentNode.rowIndex;
console.log(rowIndex);
}