click() jquery function not available on new divs

2019-02-23 11:36发布

问题:

During the running of my website i create new divs using jquery with class "a". I have defined a click() function for "a" class as follows:

$(document).ready(function() {
    $(".a").click(function(){
        $(".a").hide();
    });
});

Problem is that the new divs created with the same class do not call this function when clicked. Other divs with "a" class which are there at the beginning do. What am I doing wrong?

回答1:

$(document).delegate('.a', 'click', function() {
  $(this).hide();
});


回答2:

Try using the .live() function which should also apply for newly inserted DOM elements that match your selector:

$(document).ready(function() {
    $(".a").live('click', function(){
        $(".a").hide();
    });
});


回答3:

This might also work.

(function($) {  
  $(document).ready(function () {
    $('body').on('click', '.a', function() {
      $(this).hide();
    });
  });
}( jQuery ));

.on() attaches events to controls that are both present and not yet present.



回答4:

Use the "live" method.

http://api.jquery.com/live/