click() jquery function not available on new divs

2019-02-23 11:15发布

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?

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-23 11:36

Use the "live" method.

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

查看更多
beautiful°
3楼-- · 2019-02-23 11:37
$(document).delegate('.a', 'click', function() {
  $(this).hide();
});
查看更多
时光不老,我们不散
4楼-- · 2019-02-23 11:44

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.

查看更多
爷、活的狠高调
5楼-- · 2019-02-23 11:45

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();
    });
});
查看更多
登录 后发表回答