jQuery: How to add event handler to dynamically added HTML elements?

前端 未结 4 949
心在旅途
心在旅途 2020-12-03 12:36

I have the following code:

$(document).ready(function({
    $(\".click\").click(function(){
        alert(\' The Button Was Clicked !\');
    });
}));

相关标签:
4条回答
  • 2020-12-03 13:12

    After jQuery 1.7 the live method just points to .on() method. And I had alot trouble finding out how to bind event handler to element which is appended to the DOM after its loaded.

    $('body').live('click', '.click', function(){
       //Your code
    });
    

    This worked for me. Just a little tip for those having trouble with it also.

    0 讨论(0)
  • 2020-12-03 13:21

    UPDATE

    It's been a while since I posted this answer and things have changed by now:

    $(document).on('click', '.click', function() {
    
    });
    

    Since jQuery 1.7+ the new .on() should be used and .live() is deprecated. The general rule of thumb is:

    • Don't use .live() unless your jQuery version doesn't support .delegate().
    • Don't use .delegate() unless your jQuery version doesn't support .on().

    Also check out this benchmark to see the difference in performance and you will see why you should not use .live().


    Below is my original answer:

    use either delegate or live

    $('.click').live('click', function(){
    });
    

    or

    $('body').delegate('.click', 'click', function() {
    
    });
    
    0 讨论(0)
  • 2020-12-03 13:22

    for all the elements added dynamically to DOM at run time , please use live

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

    0 讨论(0)
  • 2020-12-03 13:34

    In reference to your code, the way to do it would be.

    $('.click').live('click', function(){
      ... do cool stuff here
    });
    

    Using the .live() function allows you to dynamically attach event handlers to DOM objects. Have fun!

    0 讨论(0)
提交回复
热议问题