我正在尝试制作一款 NYT 连接游戏,需要 16 个按钮。我使用 forEach 函数创建它们,但只知道如何在单击每个按钮时访问它。我想在所有 4 个选项正确时禁用它们。如何访问用户使用 Button.group 值选择的 4 个按钮? :
const parentElement = document.querySelector('.game-container');
wordButtons.forEach (function (b) {
const button = document.createElement('button');
button.innerText = b.word;
button.group = b.group;
button.id = b.buttonId;
button.active = false;
parentElement.appendChild(button);
button.onclick = function(){
if (button.active === false){
//case if you click it and choose it
buttonIDs.push(button.id);
buttonGroups.push(button.group);
button.active = true;
button.style.backgroundColor = "white";
} else {
//case if you un-choose it
button.active = false;
button.style.backgroundColor = "rgb(241, 215, 225)";
// remove button id from array
buttonIDs.splice(buttonIDs.indexOf(button.id));
buttonGroups.splice(buttonGroups.indexOf(button.group),1);
}
if (buttonIDs.length === 4){
if (buttonGroups.every(x => x === buttonGroups[0])){
console.log("you matched a set!");
if (button.group === buttonGroups[0]){
button.disabled = true;
};
}
}
}
})
抱歉,如果我在这里放了太多代码 - 这是我第一次在这里问问题。
我尝试从 onclick 函数的执行上下文中删除“if buttonIds length === 4”情况,希望以这种方式访问所有按钮并禁用它们,但如果我从 onclick 函数中删除它,代码块根本不执行。
我可能可以单独创建按钮并给它们编号,但这似乎是不好的形式。
我并没有百分百投入游戏......
不使用按钮元素,而使用复选框。复选框有一个状态——选中或未选中,并且可以被禁用。我使用这两个属性来决定是否选中一组中的所有复选框,然后禁用一组中的所有复选框。
在这里,我只在组中添加 2 个单词...
const words = [{
word: 'Word1',
group: 1
}, {
word: 'Word2',
group: 1
}, {
word: 'Word3',
group: 2
}, {
word: 'Word4',
group: 2
}];
words.forEach(word => {
let label = document.createElement('label');
let span = document.createElement('span');
let input = document.createElement('input');
input.name = `group_${word.group}`;
input.groupid = word.group;
input.type = 'checkbox';
span.textContent = word.word;
label.appendChild(input);
label.appendChild(span);
document.forms.game.appendChild(label);
});
document.forms.game.addEventListener('change', e => {
let form = e.target.form;
let checked = [...form.elements].filter(input => input.checked && !input.disabled);
if (checked.length == 2) {
checkGroup(e.target.groupid);
}
if (checked.length > 2) {
e.target.checked = false;
}
});
function checkGroup(groupid) {
let form = document.forms.game;
let inputs = form[`group_${groupid}`];
let checked = [...inputs].filter(input => input.checked);
if (checked.length == 2) {
[...inputs].forEach(input => input.disabled = true);
}
}
label input {
display: none;
}
label span {
display: inline-block;
padding: .2em;
margin: .2em;
background-color: lightgray;
}
input:checked+span {
background-color: darkgray;
}
input:checked:disabled+span {
background-color: green;
}
<form name="game"></form>