我正在用JavaScript構建這個多選遊戲。規則相當簡單;用戶被問到number1 + number2等於什麼,並且有4個不同的選擇答案(一個是正確的)。JS多選遊戲無法檢測到正確答案
但是,由於某些原因,在我的代碼中,無論我選擇什麼答案(即使它是錯誤的),遊戲總是告訴我,我選擇了正確的答案。
這裏是我的代碼:
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var opts = [];
for(var i=0;i<3;i++){
opts.push(findRandom(result,opts));
}
opts.push(result);
opts.sort();
for(var i=1;i<5;i++){
document.getElementById('option'+i).innerHTML = opts[i-1];
}
console.log(opts);
});
function findRandom(n,opts){
var result = 0;
while(result !=n && result == 0){
result = Math.floor(Math.random() * (n + 1));
if(opts.indexOf(result) >0){
result = 0;
}
}
return result;
}
var choices = document.querySelectorAll('.field-block');
[].slice.call(choices).forEach(function(choice){
choice.addEventListener('click', function(){
getChoice(choice);
});
});
function getChoice(){
if(choices.innerHTML = result){
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = 'Good job :) !';
} else{
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = "Wrong answer :(Try again !";
}
}
這裏是我的codepen:https://codepen.io/teenicarus/pen/Oxaaoe
自己嘗試一下,你會看到這個問題的時候了。
我該如何解決這個問題?
我感謝所有的反應