Jquery dynamic binding.on () choose parents or children?
For example,
$( "#dataTable tbody tr" ).on( "click", function() {
alert( $( this ).text() );
});
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});
.on () binds "tr" to a click event handler. The first one selects the children and registers the click event handler directly. The second selects the parent "tbody" and selects the children "tr" as an argument.
Are they both dynamic links? Do they have the same effect? What is the difference between the two?
source to share
No, only the second version is dynamic binding.
It should be easy to understand. When you have your code:
$(selector).method(arguments);
jQuery finds all the elements that match selector
at run time and names them at that time method
. If you run this code on the first page load, it will only find elements that match the selector in the original document. If the elements tr
are added dynamically, the first version won't find them, so it won't bind a click event to them.
When you use .on()
with a selector as the second argument like
$(outerSelector).on(event, innerSelector, function...);
works as follows. It finds all the elements that match outerSelector
and associates an event handler with them; these elements must exist when you call .on()
. When the event occurs, the handler checks to see if the target matches innerSelector
and then executes the callback function. Thus, it allows the event to work with dynamically added elements.
So, the general rule is that you outerSelector
should refer to a static element in a document, and innerSelector
dynamic elements.
source to share
Really dynamic
really dynamic
.
The following will bind an onclick event to everyone #dataTable tbody tr
on the page:
$( "#dataTable tbody tr" ).on( "click", function() { /*event*/ });
Another will bind an onclick event to everyone #dataTable tbody
on the page, and the event will only fire if one of its clicked children encounters a selector tr
(see Event Delegation ):
$( "#dataTable tbody" ).on( "click", "tr", function() { /*event*/ });
The second can be considered dynamic as it simulates an onclick for the specified selector, regardless of whether any of those elements exist at the time of binding. But technically, this is the event that is tied to #dataTable tbody
.
source to share