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

本小妞迷上赌 提交于 2019-12-13 08:35:43

问题


When using a jQuery delegated event handler, how do I get the descendant selector? For example, in the following table, I want to select the table row that was clicked:

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

The table is added dynamically, so I'm using a delegated event handler.

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

How can I select the tr element using the above delegated event handler?

Also, if someone has a JavaScript only solution, that would be great too.


回答1:


I put the solution (that I mentioned in comment section) to helping future readers.

You passed jQuery object as selector, you need to change the code to following, then $(this) will be the tr:

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

    // play with $tr
});

More about on here: .on()




回答2:


Few errors in your code.

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

except this your code is good

$("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>


来源:https://stackoverflow.com/questions/39417193/when-using-a-jquery-delegated-event-handler-how-do-i-get-the-descendant-selecto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!