jQuery On function for future elements?
17,029
Solution 1
For future elements inside #dataTable tbody
, your code should work. To delegate the click all the way up to the document, allowing the same handler for future <tr>
anywhere on the page, try:
$(document).on("click", "tr", function(event){
alert($(this).text());
});
Solution 2
Adding to Davids accepted answer, you can also use this solution to bind multiple events to a selector as well as all future matching elements.
For example an input element.
$(document).on({
focus:function(){
alert($(this).val());
},
blur: function(){
alert($(this).val());
}
}, 'input[type=text]');
Solution 3
This will handle all <tr>
s, no matter when they were created, but only within the currently-existing #dataTable tbody
.
It's equivalent to .delegate
.
Related videos on Youtube
Author by
Royi Namir
Updated on June 04, 2022Comments
-
Royi Namir almost 2 years
$("#dataTable tbody").on("click", "tr", function(event){ alert($(this).text()); });
is this syntax is for tr's which are already on the Page ?
and if not , What is the syntax for future tr's elements ?
-
Royi Namir over 12 yearsSo there is no difference anymore between "already in dom" vs "will be in dom" ?
-
Stefan over 12 yearsThere are still differences but delegate(), live() and on() can handle both.
-
Royi Namir over 12 years@Stefan since 1.7 I should not use live anymore and delegate is like on.... so there is no difference anymore ......right?
-
Royi Namir over 12 yearsso what youre saying is that the "on" is also for current and future dom ?
-
Stefan over 12 yearsYou´re right, you shouldn´t use
live()
since 1.7 butdelegate()
andon()
can handle a modified DOM whichclick()
doesn´t. -
David Hellsing over 12 yearsYes, as long as the inserted element is inside the element that bound the event.
-
Reign.85 almost 10 yearsExactly what i needed. I love you
-
Gavin over 8 years@RoyiNamir there is a difference. Using syntax like
$('.container elem').on('click', function(){})
is only for current elements. Using syntax like$('.container').on('click', 'elem', function(){})
handles future elements as well.