After entering html jquery event handlers do not work with / without delegate

I have a <div> list with the same html but with different values ​​inside html. The hierarchy is as follows:

 <div id="element"> <div class="likecomm"> <a class="commenticon" href="#">...some value according to the returning value...</a> </div> </div> <div id="element"> <div class="likecomm"> <a class="commenticon" href="#">...some value according to the returning value...</a> </div> </div> 

In the case, I insert html at the top of the list, which is another <div id="element> ... </div>

I have the following event handler for clicking a comment icon,

 $('.commenticon').click(function(){ $(this).closest('.actionframe').next('nav').slideToggle(300); return false; }); 

It works correctly until I inserted a new <div id="element> ... </div> . The comment icon click event handler does not match. I looked for this problem, everyone said that .delegate() should be used.

My problem is that I do not know where to use the delegate function. I used to get results from ajax to enter <div id="element> ... </div> , I used the .delegate() function in an ajax call that introduces html.

 $.ajax({ success:function(data) { var html=... // the necessary div html binded with data // prepend function call() $('.likecomm').delegate(".commenticon","click" , function() { $(this).closest('.actionframe').next('nav').slideToggle(300); return false; }); } }); 

This is currently not working. So, any ideas how to make this thing work?

+4
source share
2 answers

You need to associate the event handler with the common ancestor of the elements on which it should be run. For example, if your #element added inside a div with id from parent :

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

This will be for the HTML structure, for example:

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

The reason for this is that DOM events accumulate the tree from where they come from. The delegate method captures the event in the ancestor element and checks if it occurred in the element corresponding to the selector.

Also note that it is not valid to have duplicate id values ​​in the same document. Here I changed your element identifier values ​​to class names.

Finally, if you are using jQuery 1.7+, you should use on . It will have the same effect, but note the cancellation of the first two arguments:

 $("#parent").on("click", ".commenticon", function() { //Do stuff }; 
+13
source

You add <div id="element> ... </div> , which means that they do not initially exist. You need to add a delegate to the top level that exists. Then any .commenticon that is added under the" container "will be have a click event.

 $('#container').delegate(".commenticon","click" , function() { $(this).closest('.actionframe').next('nav').slideToggle(300); return false; }); 
0
source

Source: https://habr.com/ru/post/1397741/


All Articles