Jquery.on () from append

I am really confused how to add a click event to an element created by jquery.

Now I am generating the following elements:

$.ajax( params.... ) .done(function(item){ $.each(item, function(i, some){ a = '<p>some text</p>'; $(node).before(a); } }); 

My problem is that I am trying to add a click event to the "p" element. If I do this:

 $('p').on('click', 'p', function(){ alert('yai!'); }); 

It doesn’t show anything yet. BUt if I do this:

 $.ajax( params.... ) .done(function(item){ $.each(item, function(i, some){ a = '<p>some text</p>'; $(a).click(function(){ alert('yai!'); }); $(node).before(a); } }); 

It displays too many warnings (the same number of p elements)

What am I doing wrong?

+4
source share
2 answers

Your options:

  • (recommended) . You can associate this click on event with the parent element. This is the best method, because regardless of the number p inside the parent element, click always binds to the parent object and makes it dry and more efficient.

     $("YourParentElement").on('click', 'p', function(){ alert('yai!'); }); 
  • You can place an event handler with $("p") as a selector after the $.each . At that time, your p elements would be in the DOM, so you can bind a click handler to the element. (Disadvantage: you must attach a click handler to each p , which is sometimes overhead if you have a large number of similar p s)

     $.ajax( params.... ).done(function(item){ $.each(item, function(i, some){ a = '<p>some text</p>'; // Click() was here causing it //////// // to loop multiple times // $(node).before(a); // }); /////////////////////////////////////// // / / / moved here $("p").click(function(){ alert('yai!'); }); }); 
  • You can associate this ( p ) element with a document object that always exists, even before loading jquery. And it is not there in the API. Going on these lines is definitely not better to use live . For information on why live is evil, go here and here .

+4
source

I think you need to try under the code to bind the click event to the paragraph tag.

 $("p").click(function(){ alert("clicked"); }); 

Hope this helps you.

0
source

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


All Articles