This question has already been answered:

There is a block:

<div class="block"> </div> 

When clicking on this block, other blocks are inserted into it:

 for (i=0; i<n; i++) { $(".block").append("<div class='inner'></div>"); } <div class="block"> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> <div class="inner"></div> </div> 

How to perform a function by clicking on an element with a class. .inner ? Running a script on a click only works if the code immediately contains blocks with the class .inner , but if they are inserted via .append , then the script is no longer running.

 $(".inner").click(function(){ alert("Клик"); } 

Reported as a duplicate by members null , Visman , LEQADA , torokhkun , Vladyslav Matviienko Oct 28 '15 at 10:21 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

The click function does not bind to the filter inside JQ, but directly to the DOM object. You must create an event after adding.

 for (i=0; i<n; i++) { $("<div/>").addClass("inner").appendTo($(".block")).click(/*тут функция*/); } 

or

 for (i=0; i<n; i++) $("<div/>").addClass("inner").appendTo($(".block")); $(".block>div.inner").click(/*тут функция*/); 
  • For me, your version works as follows: the function is executed n-times in a loop, but not on a click. - Frontender
  • Rather n-time by clicking on any element with the class "inner". How to perform the function only 1 time? - Frontender