[英]Javascript: When all buttons are clicked function
Hello sir I'm practicing my vanilla javascript.您好先生,我正在练习我的香草 javascript。 I am trying to create a "Hangman Game" when the correct letters are clicked from the buttons.. You win.当从按钮上单击正确的字母时,我正在尝试创建一个“刽子手游戏”。你赢了。 I have all these buttons in queryselector(letterA to letterZ).我在查询选择器中有所有这些按钮(从字母A到字母Z)。
The problem using this function.. the winAlert = visible implements
when the letterS
was clicked (last letter of "cautious").使用此 function 的问题.. the winAlert = visible implements
letterS
“谨慎”的最后一个字母)。
So is there a way when you clicked all the letters of cautious in any order the winAlert.style.visibility = "visible"
will be execute inside the function?那么,当您以任何顺序单击所有谨慎字母时,有没有办法在 function 内执行winAlert.style.visibility = "visible"
?
I've tried everything in the last hours.. buttons.forEach
, slice etc. nothing works.在过去的几个小时里,我已经尝试了所有的buttons.forEach
, slice 等没有任何效果。
function youWonCautious() {
var buttons = [letterC, letterA, letterT, letterI, letterU, letterI, letterO, letterS]
for (var i = 0; i < buttons.length; i++) {
var button = buttons[0, 1, 2, 3, 4, 5, 6, 7];
button.onclick = function() {
winAlert.style.visibility = "visible"
}
}
}
Buttons don't automatically maintain any state about whether they were clicked.按钮不会自动维护任何关于它们是否被点击的 state。 You can do this yourself using the dataset
property of the button.您可以使用按钮的dataset
属性自己执行此操作。
Then your function can test whether all the buttons have this property set.然后你的 function 可以测试是否所有的按钮都设置了这个属性。
Or maybe you can change your buttons to checkboxes, and use the checked
property.或者,也许您可以将按钮更改为复选框,并使用checked
的属性。
function allButtonsClicked(buttons) { return buttons.every(b => b.dataset.chosen == 'true') } function youWonCautious() { var buttons = [letterC, letterA, letterT, letterI, letterU, letterO, letterS]; buttons.forEach(button => { button.dataset.chosen = 'true'; if (allButtonsClicked(buttons)) { winAlert.style.visibility = "visible"; } }); }
You can create a global array in which log the alphabets clicked by the user.您可以创建一个全局数组,在其中记录用户单击的字母。 check for the alphabets in the global array variable and answer array.检查全局数组变量和答案数组中的字母。 If matches Pass alert message else fail message to user.如果匹配则通过警报消息,否则将失败消息发送给用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.