[英]How can I infer the index of a row of a table from event?
我在表格的每一行都有一个按钮,还有一个用于 onclick 按钮的处理程序:
<button onclick="handler1(event)">aa</button>
如何从事件中确定行的索引?
请注意, “handler1”的签名不能更改,即只能将单个参数“event”传递给它。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.