使用 jQuery 委托事件处理程序时,如何获取后代选择器?

When using a jQuery delegated event handler, how do I get the descendant selector?

使用 jQuery 委托事件处理程序时,如何获取后代 selector?例如,在下面的 table 中,我想 select 被单击的 table 行:

<div id='timeline'>
    <table>
        <tr data-somedata=5><td>First Row</td></tr>
        <tr data-somedata=100><td>Another row</td></tr>
    </table>
</div>

table 是动态添加的,所以我使用的是委托事件处理程序。

$("#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>
});

我如何select tr 元素使用上面的委托事件处理程序?

此外,如果有人有 JavaScript 唯一的解决方案,那也很好。

我将解决方案(我在评论部分中提到的)用于帮助未来的读者。

您将 jQuery object 传递为 selector,您需要将代码更改为以下代码,然后 $(this) 将是 tr:

$('#timeline').on('click', 'tr', function(event){
    var $tr = $(this);

    // play with $tr
});

更多关于 on 的信息:.on()

您的代码中几乎没有错误。

1.its `timeline` not `#timeline`
2.you can simply refer as tr it should not be $('tr')

除此之外你的代码很好

$("timeline").on("click","tr",function(){
   alert($(this).attr('data-somedata'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<timeline>
    <table>
        <tr data-somedata=5><td>First Row</td></tr>
        <tr data-somedata=100><td>Another row</td></tr>
    </table>
</timeline>