我是javascript新手。我正在制作抽认卡程序。由于某些原因,尽管将变量lastPress定义为全局变量,但lastPress似乎返回undefined。但是,这不会导致JSHint错误。这是我的代码:
var i = 0;
var questions = ["1: Was the human migration caused by an ice age?", "True"];
var answer = [true, true];
var lastPress;
document.getElementById("question").innerHTML = questions[i];
function itsTrue() {
lastPress = true;
}
function itsFalse() {
lastPress = false;
}
function getAns() {
if (answer[i] == lastPress) {
document.getElementById("ans").innerHTML = "You're correct! The answer was " + lastPress;
}
else {
document.getElementById("ans").innerHTML = "We're sorry, but that is not correct. You said " + lastPress + ". The answer was " + answer[i];
}
i++;
document.getElementById("question").innerHTML = questions[i];
}
document.getElementById("true").onclick = function(){itsTrue()};
document.getElementById("true").onclick = function(){getAns()};
document.getElementById("false").onclick = function(){itsFalse()};
document.getElementById("false").onclick = function(){getAns()};
<!DOCTYPE HTML>
<html>
<head>
<title>Flash cards</title>
</head>
<body>
<p id="question">This is where the question shows up</p>
<p id="ans">This is where the result will show up</p>
<button type="button" id="true">True</button>
<button type="button" id="false">False</button>
</body>
</html>
如果要为同一单击事件定义多个功能:同样,在第二次按下您的真假按钮后,i会增加到2,因此问题[2]未定义
var i = 0;
var questions = ["1: Was the human migration caused by an ice age?", "True"];
var answer = [true, true];
var lastPress;
document.getElementById("question").innerHTML = questions[i];
function itsTrue() {
console.log('true')
lastPress = true;
}
function itsFalse() {
console.log('false');
lastPress = false;
}
function getAns() {
if (answer[i] == lastPress) {
document.getElementById("ans").innerHTML = "You're correct! The answer was " + lastPress;
}
else {
document.getElementById("ans").innerHTML = "We're sorry, but that is not correct. You said " + lastPress + ". The answer was " + answer[i];
}
i++;
console.log(i);
document.getElementById("question").innerHTML = questions[i];
}
document.getElementById("true").onclick = function(){itsTrue();getAns();};
//document.getElementById("true").onclick = function(){getAns()};
document.getElementById("false").onclick = function(){itsFalse(),getAns();};
// document.getElementById("false").onclick = function(){getAns()};
<!DOCTYPE HTML>
<html>
<head>
<title>Flash cards</title>
</head>
<body>
<p id="question">This is where the question shows up</p>
<p id="ans">This is where the result will show up</p>
<button type="button" id="true">True</button>
<button type="button" id="false">False</button>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句