After injecting html by jquery, the event handlers doesn't work with/without delegate

前端 未结 2 1119
遇见更好的自我
遇见更好的自我 2021-01-14 02:48

I have a list of

s with same html but different values inside html. The hierarchy is the following ;

相关标签:
2条回答
  • 2021-01-14 03:32

    You need to bind the event handler to a common ancestor of the elements on which it should be triggered. For example, if your #element gets appended inside a div with an id of parent:

    $("#parent").delegate(".commenticon", "click", function() {
        //Do stuff
    });
    

    This would be for an HTML structure like so:

    <div id="parent">
        <div class="element">
    
        </div>
        <div class="element">
    
        </div>
    </div>
    

    The reason this works is that DOM events bubble up the tree from the point at which they originate. The delegate method captures the event at an ancestor element and checks whether or not it originated at an element matching the selector.

    Also note that it's invalid to have duplicate id values in the same document. Here I've changed your element ID values to class names instead.

    Finally, if you are using jQuery 1.7+ you should use the on method instead. It will have the same effect, but notice the reversal of the first 2 arguments:

    $("#parent").on("click", ".commenticon", function() {
        //Do stuff
    };
    
    0 讨论(0)
  • 2021-01-14 03:33

    You are adding <div id="element> ... </div> which means that those doesn't exist initially. You need to add delegate to upper level that exists. Then any .commenticon that is added under the "container" will have click event.

    $('#container').delegate(".commenticon","click" , function() {                      
        $(this).closest('.actionframe').next('nav').slideToggle(300);
        return false;
    }); 
    
    0 讨论(0)
提交回复
热议问题