有没有一种方法可以检查单击的按钮的textContent是否匹配数组中的任何值?

时间:2020-08-29 08:43:06

标签: javascript

我正在制作一个《 Hangman》游戏,我的代码需要帮助。我希望我的代码具有一个将单击按钮的textContent属性作为输入的函数,以及另一个接受按钮本身的参数。如果所单击的按钮与我的数组中的按钮具有正确的textContent,则应添加一个correct类,如果错误,则应添加一个wrong类按钮为红色。我当前的代码无法实现这一点,相反,它为wrong类提供了所有按钮,请提供有关修复的建议。谢谢。

功能

function checkAnswer(userChoice, userButton) {

    for (var i = 0; i < spellingOfWord.length; i++) {

        if (userChoice == spellingOfWord[i]) {

            userButton.classList.add("correct");

            setTimeout(function() {
                userButton.classList.add("hidden");
            }, 400);

        } else {
            userButton.classList.add("wrong");

            setTimeout(function() {
                userButton.classList.add("hidden");
            }, 400);

        }

        console.log(spellingOfWord[i]);
    }
}

我在哪里调用该功能

for (var i = 0; i < document.querySelectorAll("button").length; i++) {

            document.querySelectorAll("button")[i].addEventListener("click", function () {

                checkAnswer(this.innerHTML, this);

            });
}

spellingOfWord数组的示例

注意:这只是一个例子。

var spellingOfWord = gameWords[randomNumber].split("");

// In the browser, when console logging it, I get back:

["f", "o", "r"];

// Now I want to take the `textContent` of the button that was clicked and check against all the values of this array, but the code does not work, please advice.

1 个答案:

答案 0 :(得分:1)

您的for循环在每次迭代时添加类,因此您的按钮将具有多个错误的类,并且可能有一些正确的地方,您需要做的是假设该类在开始时是错误的,并且如果找到它,则将其更改为正确的并打破循环,然后应用课程

let buttonClass = 'wrong'
for (var i = 0; i < spellingOfWord.length; i++) {

    if (userChoice == spellingOfWord[i]) {
        buttonClass = "correct";
        break;
    } 

    console.log(spellingOfWord[i]);
}

userButton.classList.add(buttonClass);

setTimeout(function() {
   userButton.classList.add("hidden");
}, 400);

或者按照建议可以做

    if (spellingOfWord.includes(userChoice)) {
        userButton.classList.add("correct");

        setTimeout(function() {
            userButton.classList.add("hidden");
        }, 400);

    } else {
        userButton.classList.add("wrong");

        setTimeout(function() {
            userButton.classList.add("hidden");
        }, 400);

    }