简体   繁体   English

为什么我的计数器每次加一以上?

[英]Why is my counter adding more than one each time?

I am creating a test using jQuery, but can't work out why when the correct answer is used my counter variable, count , seems to go up by more than one. 我正在使用jQuery创建测试,但无法弄清楚为什么使用正确答案时,我的计数器变量count似乎增加了不止一个。

function nextQuestion(){
    $('#submit').show();
    $('#next').hide();
    $('#result').text('');
    $('#value').val('');
    randomNumber = Math.floor((Math.random() * words.length));
    $('#englishWord').text(words[randomNumber][0]);
    $('#submit').click(function(){
        if ($('#value').val() == words[randomNumber][1])
        {
            $('#result').text("You are correct, well done");
            $('#submit').hide();
            $('#next').show();

            $('#next').click(function(){
                count = count + 1;
                $('#score').text(count); 
                nextQuestion();              
            });
        }
        else 
        {
            $('#result').text("That is incorrect, try again");
            count = 0;
            $('#score').text(count);
        }
    });
}

count is increasing by more than one each time there is a click on #next because you are adding multiple anonymous listeners to the click event of the #next element. 每次单击#next count就会增加一个#next因为您#next元素的click事件添加多个匿名侦听器。 Each of those functions is independently adding 1 to count . 这些功能中的每一个都独立地加1 count Thus, when #next is clicked, count goes up 1 for each anonymous listener you have added to the click event on the #next element. 因此,当单击#next时,对于您添加到#next元素上的click事件的每个匿名侦听器, count都将增加1。

Every time there is a click on #submit and $('#value').val() == words[randomNumber][1] you execute: 每次单击#submit$('#value').val() == words[randomNumber][1]都会执行:

$('#next').click(function(){
    count = count + 1;
    $('#score').text(count); 
    nextQuestion();              
});

This results in a new anonymous function being added as a listener to the #next element's click event in addition to any ones already listening for that event. 这将导致一个新的匿名函数被添加为#next元素的click事件的侦听器,而其他任何匿名函数#next在监听该事件。 Thus, each time there is a click event on #next tehre are multiple functions called which each increases the count by 1. The total amount of the increase for each click on #next depends on how many functions you have listening to that event. 因此,每次在#next上有一个click事件时, #next调用多个函数,每个函数会将count增加1。 #next上的每次单击所增加的#next取决于您侦听该事件的功能。

You have the same problem with the click event for the #submit element. #submit元素的click事件存在相同的问题。 This causes count to increase even further by adding even more listeners to the click event of the #next element. 通过将更多侦听器添加到#next元素的click事件中,这将导致count进一步增加。 The first time #submit is clicked one listener is added. 首次单击#submit将添加一个侦听器。 On the the second #submit click two listeners to the #submit click event each add another listener to the #next click event making a total of 3 listeners on that event. 在第二个#submit单击上,两个侦听器分别发送给#submit click事件,每个侦听器将另一个侦听器添加到#next click事件,从而使该事件总共有3个侦听器。 Thus, count goes up by 3. This continues to scale as you add more and more listeners to each event. 因此, count增加了3。随着向每个事件添加越来越多的侦听器,此count将继续扩展。

Have your code add the event listeners only once 让您的代码仅添加一次事件监听器

The solution to this is to only assign those click events once: 解决方案是仅将这些点击事件分配一次:

$('#submit').click(function(){
    if ($('#value').val() == words[randomNumber][1])
    {
        $('#result').text("You are correct, well done");
        $('#submit').hide();
        $('#next').show();
    }
    else 
    {
        $('#result').text("That is incorrect, try again");
        count = 0;
        $('#score').text(count);
    }
});

$('#next').click(function(){
    count = count + 1;
    $('#score').text(count); 
    nextQuestion();              
});

function nextQuestion(){
     $('#submit').show();
     $('#next').hide();
     $('#result').text('');
     $('#value').val('');
     randomNumber = Math.floor((Math.random() * words.length));
     $('#englishWord').text(words[randomNumber][0]);
}

Alternately, use a named function and rely on addEventListener() to ignore your attempts to add identical listeners. 或者,使用命名函数并依赖addEventListener()来忽略添加相同侦听器的尝试。

An alternate solution is to use a single named function, which is defined in a scope such that it is not redefined each time the code adding it is called. 另一种解决方案是使用单个命名函数,该函数在范围内定义,这样,每次调用添加该函数的代码时就不会重新定义该函数。 Listeners which are not added using event attributes (eg <div onclick="doSomething();"> ) are added using addEventListener() (jQuery uses this method inside the various methods it provides for adding event listeners). 未使用事件属性 (例如<div onclick="doSomething();"> )添加的侦听器使用addEventListener()添加(jQuery在其提供的用于添加事件侦听器的各种方法中使用此方法)。 If you try to add the same function, using the same values for the other parameters to addEventListener() , then the additional listeners are discarded . 如果您尝试添加相同的函数,并且对addEventListener()的其他参数使用相同的值,则其他监听器将被丢弃 That means that even if you try to add the same function, with the same parameters, more than once, it will only be called once per event. 这意味着即使您试图多次添加具有相同参数的相同函数,每个事件只会调用一次。 With an anonymous function, the function is separately defined each time that code is run. 使用匿名函数,每次运行代码时都会分别定义该函数。 Thus, while the code is the same, the function that is defined is separate from any prior time the code has run. 因此,虽然代码相同,但是定义的功能与代码运行之前的任何时间是分开的。 As a result, multiple copies get added. 结果,添加了多个副本。

However, just because the function has a name does not mean that it is defined in a scope that will result in it not being redefined each time it is added. 但是,仅因为函数具有名称并不意味着在某个作用域中对其进行了定义,否则将导致每次添加该函数时都不会对其进行重新定义。 For instance, in the above code, if the function for the #next listener was defined within the #submit listener, and even if it had a name, it would still be redefined every time the #submit listener was run. 例如,在上面的代码,如果该功能#next监听器的内定义#submit监听器,即使它有一个名字,它仍然会在每次重新定义时间#submit监听器运行。 To prevent the function from being redefined, the key is how and where the function is defined, not just that it is a named function. 为了防止函数被重新定义,关键在于函数的定义方式和位置,而不仅仅是其是命名函数。 However, in order to refer to that function it must have a name, or otherwise be associated with a variable. 但是,为了引用该函数,它必须具有名称,否则必须与变量关联。 Thus, you will generally find that there is an assumption made when someone says a "named function" that it is defined in a way that it is not, normally, redefined. 因此,您通常会发现,当有人说“命名函数”时,通常以不重新定义的方式进行定义。

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

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