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

六眼飞鱼酱① 提交于 2019-12-19 09:27:34

问题


For example,

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

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

.on() binds "tr" with click event handler. The first one select children and register click event handler directly. The second one select parent "tbody", and select children "tr" as an argument.

Are they both dynamic binding? Do they have the same effect? What is the difference between these two?


回答1:


No, only the second version is dynamic binding.

It should be simple to understand. When you have code like:

$(selector).method(arguments);

jQuery finds all the elements that match the selector at the time you execute the code, and calls the method on them at that time. If you execute this code when the page is first loaded, it will only find the elements that match the selector in the initial document. If the tr elements are added dynamically, the first version will not find them, so it will not bind the click event to them.

When you use .on() with a selector as the second argument, e.g.

$(outerSelector).on(event, innerSelector, function...);

it works as follows. It finds all the elements that match outerSelector, and binds a handler for the event to them; these elements have to exist when you call .on(). When the event occurs, the handler checks whether the target matches innerSelector, and then it executes your callback function. This is how it allows the event to work on dynamically-added elements.

So the general rule is that outerSelector should refer to a static element in the document, while innerSelector refers to the dynamic elements.




回答2:


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.



来源:https://stackoverflow.com/questions/25655988/jquery-dynamic-binding-on-select-parents-or-children

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