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?
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
.
来源:https://stackoverflow.com/questions/25655988/jquery-dynamic-binding-on-select-parents-or-children