click() jquery function not available on new divs

空扰寡人 提交于 2019-12-30 22:26:32

问题


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/



来源:https://stackoverflow.com/questions/6192458/click-jquery-function-not-available-on-new-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!