jQuery with elements generated dynamically

前端 未结 6 1559
旧巷少年郎
旧巷少年郎 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 16:45

    Thanks everybody.

    Somehow I thought elements were added to the DOM automatically by jQuery just by adding them anywhere.

    I've also found some extra information on the topic:

    http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F

    http://learningjquery.com/2008/03/working-with-events-part-1

    http://learningjquery.com/2008/05/working-with-events-part-2

    Just in case somebody else needs it.

    0 讨论(0)
  • 2021-01-19 16:50

    If you have jQuery 1.3 or later, try using live for adding events to dynamically generated elements:

    $('.whatever').live("click", function() {
      alert("ALERT!");
    });
    
    0 讨论(0)
  • 2021-01-19 16:52

    Also look at reglib, a similar library that allows for the style of programming you're looking for.

    0 讨论(0)
  • 2021-01-19 16:53

    You need to rebind it.

    function bindme(){
        $('.whatever').click(function(){
            alert('binded');
        });
    };
    
    bindme();
    
    //function that will generate something
    
    function foo(){
       $('.whatever').val('oryt');
       bindme();//rebind itagain
    }
    
    0 讨论(0)
  • 2021-01-19 17:05

    Also, there's an excellent plugin for jQuery which takes care of this, called livequery

    0 讨论(0)
  • 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.

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