Jquery button does not respond to click method

so I dynamically create a paragraph with jquery using the append method, and I want to add a click event to it, but for some reason the click event does not work, I know that the solution is probably simple, but I am new to jquery and would be I appreciate any help ... I know that the code inside the function works because I tested it with a static button, it just does not work with a dynamic one. Thanks for any help

here is my code

$(this).parent().parent().children("div").append("<p class='tryAgain'>Try Again</p>"); 

click function code

 $(".tryAgain").click(function() {......} 
+4
source share
5 answers

Everything that you add to the DOM after document.ready has been fired needs to be used . live or . delegate to add an event handler to the newly added item.

For instance:

 $('.tryAgain').live("click", function() {...}); 

If you are using jquery 1.7+ you should use . :

 $(document).on("click", ".tryAgain", function(){ ... }); 
+7
source

Try $. live o $. delegate .

+1
source

Using:

 $('.tryAgain').live('click', function() { .... }); 
+1
source

There is an alternative to using live events, you can add a handler when creating an element as follows:

 $("<p>Try Again</p>", { "class": "tryAgain", click: function(){ //YOUR CLICK HANDLER } }).appendTo($(this).parent().parent().children("div")); 
0
source

I think you can attach the click event right there when you create a new p tag, like this:

 $(this).parent().parent().children("div").append( $('<p>').addClass('tryAgain').click(function(){ alert('test'); })); 
0
source

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


All Articles