[英]How do I select all elements with the same class?
我正在用 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 :)";
}
}
但是,通过这样做,我只能单击第一个“字段块”div,而不能单击其他 div。
这是我的项目的完整代码笔:
https://codepen.io/teenicarus/pen/Oxaaoe
如何选择所有 div,以便用户可以单击所有 div 而不仅仅是第一个?
我感谢所有的回应
问题是因为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 :)";
}
}
但是,通过这样做,我只能单击第一个“字段块”div,而不能单击其他 div。
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 );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.