Javascript 是否在jquery.click函数之外使用变量?
我想在jquery之外调用一个局部变量totalYes。单击函数。要做到这一点,我应该让它成为一个全局变量,对吗?最初,代码看起来像:Javascript 是否在jquery.click函数之外使用变量?,javascript,jquery,Javascript,Jquery,我想在jquery之外调用一个局部变量totalYes。单击函数。要做到这一点,我应该让它成为一个全局变量,对吗?最初,代码看起来像: var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12]; var answers2 = [answers2array12items]; $("#submmit").click(functi
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);
});
所以我选择了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);
});
var answers=[thing1,thing2,thing3,thing4,thing5,thing6,thing7,thing8,thing9,thing10,thing11,thing12];
var answers2=[answers2阵列12项];
var totalYes=0;
$(“#子mmit”)。单击(函数(){
函数checkAnswers(){
对于(var i=0;i,每次用户输入新答案时,您的代码都会搜索完整的答案列表。因此,每次调用时,您的单击处理程序中的测试都会对当前和所有以前的答案成功,这解释了totalYes
变量的增量模式
补救措施:将inittotalYes
设置为0,作为单击处理程序中的第一条指令。fiddle演示问题最好进行调试。我怀疑您实际上有两个都在运行的事件处理程序。@andryuuuu87如果可能,可以发布html
?例如,html
用于$(“submmit”)
,$(“total”)
?谢谢。如果问题仍然存在,您可以使用.one()方法代替单击
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);
});
<div class="nextsa1" id="total"><strong>TOTAL</strong></div>
<input type="button" id="submmit" value="GO">