JQuery function executed several times for each element

I have a simple script that generates a div element every second using setInterval. The problem I am facing is that addScore () runs once for each item in the window. Thus, if there are four goals generated, the addScore () function is run four times.

<div class="wrap"> <div class="intro"> <p>Simply press go and click the circles as fast as you can!</p> <button class="go" type="button">Go!</button> </div> </div> <script type="text/javascript"> var score = 0; // Starting score for game function addScore(){ score++; console.log(score); } function spawnTargets() { $(".wrap").append("<div class='target'>Hello</div>"); $(".target").click(function(){ $(this).hide(); addScore(); }); } $(".go").click(function() { $(".intro").toggle(); setInterval(spawnTargets, 1000); }); </script> 
+4
source share
2 answers

When you add a click-event event to .target, you do this with all the divs you added before! Use this instead:

 <script type="text/javascript"> var score = 0; // Starting score for game function addScore(){ score++; console.log(score); } function spawnTargets() { $(".wrap").append("<div class='target'>Hello</div>"); } $(".go").click(function() { $(".intro").toggle(); setInterval(spawnTargets, 1000); }); $(".wrap").on('click', '.target', function(){ $(this).hide(); addScore(); }); </script> 

.on-function adds an event handler to the parent element and filters the click elements that come from .target.

+4
source

You associate events with a few clicks when a function call is ever called

 function spawnTargets() { $(".wrap").append("<div class='target'>Hello</div>"); $(".target").click(function(){ $(this).hide(); addScore(); }); } 

Instead you need to delegate the event

Change

 $(".target").click(function(){ 

to

 $('.wrap').on("click", ".target", function(){ 

And move it out of function

code

 var score = 0; // Starting score for game function addScore() { score++; console.log(score); } function spawnTargets() { $(".wrap").append("<div class='target'>Hello</div>"); } $('.wrap').on("click", ".target", function () { $(this).hide(); addScore(); }); $(".go").click(function () { $(".intro").toggle(); setInterval(spawnTargets, 1000); }); 
0
source

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


All Articles