在jquery.click函数之外使用变量?

时间:2014-04-17 07:00:31

标签: javascript jquery

我想在jquery .click函数之外调用局部变量totalYes。要做到这一点,我应该把它变成一个全局变量,对吗?最初,代码看起来像:

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12];

var answers2 = [answers2array12items];

$("#submmit").click(function() {
    var totalYes=0;
    function checkAnswers() {
        for(var i=0; i<answers.length; i++) {
            var userAnswer = document.getElementById("b"+i).value.toLowerCase();
            if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) {
                totalYes++;
                $("#correcto").show();
            } else {
                $("#incorrecto").show();
            }
        }
    }
    checkAnswers();
    alert(totalYes);
});

然而,它工作正常,但是,我想在它中使用它:

$("total").click(function(){
    alert(totalYes);
});

所以我接受了全部,并且在功能之外进行了全局&#34;新版本是:

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12];

var answers2 = [answers2array12items];

var totalYes = 0;

$("#submmit").click(function() {
    function checkAnswers() {
        for(var i=0; i<answers.length; i++) {
            var userAnswer = document.getElementById("b"+i).value.toLowerCase();
            if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) {
                totalYes++;
                $("#correcto").show();
            } else {
                $("#incorrecto").show();
            }
        }
    }
    checkAnswers();
    alert(totalYes);
});

但是在新代码中,不是为每个正确的答案添加1到totalYes,而是像这样增加totalYes:&#34; 1,2,3,4,5,6,7,8,9,10, 11,12&#34;,它增加为:&#34; 1,3,6,10,15,21,27,33,39,46,54&#34;。我尝试在totalYes ++中更改checkAnswers()中的totalYes修饰符; to totalYes + = 1;,但问题仍然存在。

另外,我想知道为什么警报框每次都会显示两次,而不只是一次?

编辑:这里是#total和#submmit的html和css:

<div class="nextsa1" id="total"><strong>TOTAL</strong></div>

<input type="button" id="submmit" value="GO">

1 个答案:

答案 0 :(得分:1)

您的代码似乎每次在用户输入新答案时调用完整的答案列表。因此,在每次调用时,Click Inside处理程序中的Test对于当前和所有先前的答案都是成功的,这解释了totalYes变量的Delta模式。

补救措施:将totalYes初始化为0作为Click处理程序中的第一条指令。

相关问题