【发布时间】:2017-01-17 22:28:12
【问题描述】:
使用 jQuery 委托事件处理程序时,如何获取后代选择器?例如,在下表中,我想选择被点击的表格行:
<div id='timeline'>
<table>
<tr data-somedata=5><td>First Row</td></tr>
<tr data-somedata=100><td>Another row</td></tr>
</table>
</div>
表格是动态添加的,所以我使用的是委托事件处理程序。
$("#timeline").on('click', $("tr"), function(event){
console.debug($(this)); // This selects the entire #timeline
console.debug(event.target); // This selects the <td> element, not the <tr>
});
如何使用上述委托事件处理程序选择 tr 元素?
另外,如果有人只有 JavaScript 的解决方案,那也太好了。
【问题讨论】:
-
$("#timeline").on('click', $("tr"), function(event){语法不正确。如果语法正确,$(this)将是被点击的 tr。 api.jquery.com/on -
把代码改成
$("#timeline").on('click', "tr", function(event),那么$(this)就是tr -
将 $("tr") 更改为 "tr" 解决了问题,谢谢。
标签: javascript jquery event-handling jquery-events