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

风格不统一 提交于 2019-12-01 08:56:31

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.

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.

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