我正在用JavaScript构建这个游戏。这是一个简单的游戏:你被问到number1 + number2等于什么,你有4种不同的选择(只有一个答案是正确的)。
我有4个不同选项的4个不同的div,都有'.field-block'类。这就是我尝试做的事情:
var choice = document.querySelector('.field-block');
choice.addEventListener('click', getChoice);
function getChoice(){
if(choice.innerHTML != result){
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else{
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be affraid to try again :)";
}
}
然而,通过这样做我只能点击第一个'field-block'div而不是其他的div。
这是我项目的完整代码:
https://codepen.io/teenicarus/pen/Oxaaoe
如何选择所有div,以便用户可以点击所有div而不仅仅是第一个?
我感谢所有回复
答案 0 :(得分:0)
问题是因为querySelector()
返回单个项目。使用querySelectorAll()
检索所有实例。然后你可以遍历它们:
document.querySelectorAll('.field-block').forEach(function(field) {
field.addEventListener('click', function() {
getChoice(this);
});
})
function getChoice(choice){
if (choice.innerHTML != result) {
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else {
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be afraid to try again :)";
}
}
答案 1 :(得分:0)
然而,通过这样做,我只能点击第一个 “field-block”divs而不是其他的。
querySelector
只返回一个元素,您需要使用querySelectorAll
var choices = document.querySelectorAll('.field-block');
[].slice.call(choices).forEach( function( choice ){ //iterate and assign event handler to them individually
choice.addEventListener('click', function(){
getChoice(choice);
});
});
function getChoice(choice){
if(choice.innerHTML != result){
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else{
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be affraid to try again :)";
}
}
或更多更简单的jquery版本
$('.field-block').click( function(){
getChoice( this );
});