简体   繁体   English

JQuery函数为每个元素运行多次

[英]JQuery Function Running Multiple times for Each Element

I have a simple script that spawns a div element every second using setInterval. 我有一个简单的脚本,每秒使用setInterval生成一个div元素。 The problem I am facing is that the addScore() fires once for each element in the window. 我面临的问题是addScore()会为窗口中的每个元素触发一次。 So if there are four targets spawned, the addScore() function runs four times. 因此,如果生成了四个目标,则addScore()函数将运行四次。

<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>

When you add the click-event to the .target, you do it with all the divs you previously added! 当您将click事件添加到.target时,您可以使用之前添加的所有div来执行此操作! 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>

The .on-function adds the event handler to the parent element and filters for click-elements that came from .target. .on-function将事件处理程序添加到父元素,并过滤来自.target的click元素。

You are binding multiple click events , when ever a call to the function is made 在对函数进行调用时,您将绑定多个单击事件

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 to outside the 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM