我正在尝试创建一个非常基本的JS问答游戏。除了一段代码,几乎所有东西都可以工作。当您在最后一个问题上点击了第三个单选按钮时,您必须双击该按钮才能使“ if else”语句正确。如果我检查前两个单选按钮,则一切正常。我不明白为什么。
// VARIABLES
var all = {
question: ['Quante dita ha una mano?', "Qual è la capitale del Marocco", "Cosa si mangia in Spagna?" ],
response: [['uno', 'due', 'cinque'],['Marrakesh', 'Dubai', 'Roma'], ['Paella', 'Salsiccia', 'Fish']]
}
var i = 0;
var storage = [];
// TITLE
var title = document.getElementById("title");
//LABELS
var label1 = document.getElementById('risposta1');
var label2 = document.getElementById('risposta2');
var label3 = document.getElementById('risposta3');
// INPUTS
var inputs = document.querySelectorAll('input[type="radio"]')
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var input3 = document.getElementById('input3');
// DISPLAY ANSWER
function displayAnswer(){
if(all.response[i] != undefined){
title.innerHTML = all.question[i];
label1.innerHTML = all.response[i][0];
label2.innerHTML = all.response[i][1];
label3.innerHTML = all.response[i][2];
}
}
displayAnswer();
document.querySelector('#btn').addEventListener("click", function(e){
inputs.forEach(function(input){
if(i <= (all.question.length - 1)){
if(input.checked === true){
console.log(e);
console.log(input3);
console.log(input.value);
storage.push(input.value);
i++;
displayAnswer();
console.log(i);
}
}
else {
console.log("Your score is: " + storage);
document.getElementById( 'content' ).style.display = 'none';
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content">
<h1 id="title"></h1>
<label id="risposta1"></label>
<input id="input1" type="radio" name="test" value="1" ><br>
<label id="risposta2"></label>
<input id="input2" type="radio" name="test" value="2" ><br>
<label id="risposta3"></label>
<input id="input3" type="radio" name="test" value="3"> <br>
<button id="btn">Invia</button>
</div>
<script src="app.js"></script>
</body>
</html>
在控制台中没有错误。