How to register an event on elements that do not yet exist?

I am trying to register an event on such elements:

$(document).ready(function() {
   $('.classname').change(function(){
       alert ('This line is never triggered');
   });
});

But the problem is that .classname elements are later loaded into dom using ajax. So, how to register an event in this case? Is it possible to do this only once (I mean, not every time a new element appears?)

+5
source share
3 answers

In addition to answers suggesting use live(), you can also use delegate(), for example:

$('form').delegate('.classname', 'change', function(){
    alert("This will alert when the newly-added element registers a 'change' event.");
});

For an delegateelement for assigning a selector ( .classname') - , in this case $('form')must exist in the DOM at the time of the assignment.


, , ( "" "" ) :

JS Fiddle demo.

stopPropagation() , delegate(), , delegate() -d , ( ), .

, , OP:

, , - stopPropagation, live ! ?

jQueryAPI ( ):

... , .delegate(), , ...

/ , , , ($('.classname')) delegate() -d ($('form')) stopPropagation() delegate().

:

+5

on(), live() :

$(document).ready(function() {
   $( document ).on('change', '.classname', function(){
       alert ('This line is never triggered');
   });
});
+14

live, :

$(document).ready(function() {
   $('.classname').live('change',function(){
       alert ('This line is never triggered');
   });
});

.

+2

All Articles