为什么我的计数器每次加一以上? [英] Why is my counter adding more than one each time?

查看:166
本文介绍了为什么我的计数器每次加一以上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery创建测试,但无法弄清楚为什么使用正确答案时,我的计数器变量count似乎增加了一个以上.

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.

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);
        }
    });
}

每次单击#next时,

推荐答案

count都会增加一个以上,因为您要将多个匿名侦听器添加到click事件中#next元素.这些功能中的每一个都独立地将1添加到count.因此,当单击#next时,对于添加到#next元素上click事件的每个匿名侦听器,count都会增加1.

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. Each of those functions is independently adding 1 to 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.

每次执行一次#submit$('#value').val() == words[randomNumber][1]时都单击一次:

Every time there is a click on #submit and $('#value').val() == words[randomNumber][1] you execute:

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

这将导致一个新的匿名函数被添加为#next元素的click事件的侦听器,以及已经侦听该事件的任何匿名函数.因此,每次在#next上发生一个click事件时,都会调用多个函数,每个函数会将count都加1.每次单击#next所增加的总金额取决于您拥有多少个函数.听那个事件.

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

对于#submit元素的click事件,您有相同的问题.通过向#next元素的click事件添加更多的侦听器,这会导致count进一步增加.第一次单击#submit时,将添加一个侦听器.在第二个#submit上,单击两个#submit click事件的侦听器,每个侦听器将另一个侦听器添加到#next click事件,从而使该事件总共3个侦听器.因此,count上升3.随着向每个事件添加越来越多的侦听器,此比例将继续扩展.

You have the same problem with the click event for the #submit element. This causes count to increase even further by adding even more listeners to the click event of the #next element. The first time #submit is clicked one listener is added. 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. Thus, count goes up by 3. This continues to scale as you add more and more listeners to each event.

解决方案是仅将这些点击事件分配一次:

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]);
}

或者,使用命名函数并依赖 忽略您添加相同侦听器的尝试.

另一种解决方案是使用单个命名函数,该函数在范围内定义,这样,每次调用添加该函数的代码时就不会重新定义该函数.未使用事件属性添加的侦听器(例如<div onclick="doSomething();">)使用 addEventListener() 添加(jQuery在它提供的用于添加事件侦听器的各种方法中使用了此方法).如果您尝试添加相同的功能,并为addEventListener()的其他参数使用相同的值,则

Alternately, use a named function and rely on addEventListener() to ignore your attempts to add identical listeners.

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 (e.g. <div onclick="doSomething();">) are added using addEventListener() (jQuery uses this method inside the various methods it provides for adding event listeners). If you try to add the same function, using the same values for the other parameters to addEventListener(), then the additional listeners are discarded. 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.

但是,仅由于函数具有名称并不意味着在某个作用域中对其进行了定义,这将导致在每次添加该函数时都不会对其进行重新定义.例如,在上面的代码中,如果#next侦听器的函数是在#submit侦听器内定义的,即使它具有名称,每次运行#submit侦听器时仍会重新定义它.为了防止函数被重新定义,关键在于函数的定义方式和定义位置,而不仅仅是它是一个命名函数.但是,为了引用该函数,它必须具有名称,否则必须与变量关联.因此,您通常会发现,当有人说命名函数"时,通常会以不重新定义的方式进行定义.

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

这篇关于为什么我的计数器每次加一以上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆