Unable to set click event handler on dynamically generated content

I have a code like this:

$('.play').on( 'click', function(){ console.log('click'); }); 

The .play element .play dynamically created using the $('.game').html('<span class="paly">Play</span>') . However, I do not see anything in my console log when I click on this range. What am I doing wrong?

Thanks.

PS: I am using jQuery 1.7.1

+6
source share
8 answers

Do not use live() - it is deprecated. Use on() instead, but use it for the parent to delegate the event, for example:

 $('#parentOfPlay').on('click', '.play', function(){ console.log('click'); }); 
+12
source

You can use live (which is now deprecated in 1.7.1, so you really shouldn't use it) or do it with it turned on, but you, where you do 'on' wrong.

 $(document).on('click', '.play', function(){ console.log('click'); }); 
+1
source

Here's a good look at what to use and when. fooobar.com/questions/905925 / ...

.on will give you the effect you are looking for, but you need to do this in the document selector and put the class selector in the .on call.

 $(document).on( 'click', '.play', function(){ console.log('click'); }); 
0
source

the .play selector .play looking for a container with this class, so you need to generate the code with

 $('.game').html('<span class="play">Play</span>'); 
0
source

.html() sets the contents of all blocks for which the game uses a class with the name of the game. You have not created any .play class, so $(".play") gives nothing. The click function is not attached to anything, and nothing is displayed on the console. Try to make $(".game").on("click",function(){});

0
source

Try

 $(document).on('click', '.play' function(){ console.log('click'); }); 
-1
source

Try the following:

 $('.play').live( 'click', function(){ console.log('click'); }); 
-2
source

Are you sure that the ".play" element already exists while executing your code? Or maybe it was created later in the code .. It could be a problem with the order.

edit: If you want it to be dynamic, use "live" instead of "on" as suggested by others :)

-2
source

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


All Articles