jQuery with elements generated dynamically

前端 未结 6 1605
旧巷少年郎
旧巷少年郎 2021-01-19 16:14

I\'ve been working with jQuery for a pair of weeks and I\'ve noticed it works fine with objects that are in the original HTML document, but when I generate a new element usi

6条回答
  •  梦谈多话
    2021-01-19 17:07

    Thats because the : (corrected)

    $('.whatever').click(function() {
      alert("ALERT!");
    });   
    

    Means, in literal terms:

    Find all elements currently on the page that have the class ".whatever"
    Foreach element in that result set, bind this function to its click event
    

    so naturally, adding a new DOM element wont automagically apply the click.

    the best way to solve this is create bindings during your insert phase, ie:

      var x = document.createElement("span"); 
      $(x).click(function(){ });  //etc 
      $(somcontiner).append(x); 
    

    Warning on simply rebinding everything

    If done wrong, it can lead to undesired effects, ie, making the number of times the event triggers something increase. To stop this, you may need to first unbind them to delete the previous passes binds.

    ie,

    $(x).click(foo); 
    $(x).click(bar);  //foo and bar should both execute. 
    

    so to stop this, you need

    $(x).unbind("click");
    $(x).click(foo); 
    

    in the rebind.

提交回复
热议问题