gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:22:12 47 4
gpt4 key购买 nike

我想在 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);
});

所以我采用了totalYes,并将其设置为“全局”,位于函数之外。新版本是:

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

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

另外,我想知道,为什么警告框每次都会出现两次,而不是一次?

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

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

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

最佳答案

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

补救措施:将 totalYes 初始化为 0,作为单击处理程序内的第一个指令。

关于javascript - 在 jquery.click 函数之外使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23126580/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com