jquery dynamic binding .on() select parents or children?

前端 未结 2 885
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 12:26

For example,

$( \"#dataTable tbody tr\" ).on( \"click\", function() {
  alert( $( this ).text() );
});

$( \"#dataTable tbody\" ).on( \"click\", \"tr\", fun         


        
2条回答
  •  既然无缘
    2021-01-14 12:54

    Neither is really dynamic, so to speak.

    The following will bind the onclick event to every #dataTable tbody tr on the page:

    $( "#dataTable tbody tr" ).on( "click", function() { /*event*/ });
    

    The other will bind an onclick event to every #dataTable tbody on the page, and the event will only fire if one of its clicked descendents meets the selector tr (see Event Delegation):

    $( "#dataTable tbody" ).on( "click", "tr", function() { /*event*/ });
    

    The second can be considered dynamic because it simulates an onclick for the specified selector, whether or not any of those elements exist at the time of binding. But technically it's an event that's attached to #dataTable tbody.

提交回复
热议问题