jQuery - cannot bind events to dynamic elements?

后端 未结 6 568
借酒劲吻你
借酒劲吻你 2021-01-13 07:58

I\'ve come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $(\') and inserts i

6条回答
  •  孤城傲影
    2021-01-13 08:15

    You have various options. You can bind to the element or to the document. 
    

    BIND TO DOCUMENT:

     $(document).on("click", "a.foo", function(event){
    //do stuff here 
     });
    

    When you bind to a document, you can freely create and destroy a.foo elements and they will all respond to your function.

    BIND TO ELEMENT:

    $("a.foo").on("click", function(event){
    //do stuff here
      });
    

    When you bind to an element, the function is bound to all previously existing elements ONLY. So make sure you do this at the end of document load or at the end of your function.

    I would recommend always binding to document!

提交回复
热议问题