【问题标题】:Correct answer button green正确答案按钮绿色
【发布时间】:2022-02-13 20:31:33
【问题描述】:

我正在创建一个测验,我尝试在正确时将答案按钮变为绿色,在不正确时将答案按钮变为红色,然后保存此信息并转到下一个问题。但是目前的代码不起作用。这是我的 JavaScript 代码:

let shuffledQuestions, currentQuestionIndex;

const setNextQuestion = () => {
    showQuestion(shuffledQuestions[currentQuestionIndex]);
}

const showQuestion = (gameData) => {
    questionElement.innerText = gameData.question;
    let answersBlock = '';
    gameData.answer.forEach((answer, index) => {
        const answerButton = `
            <div class="answers-wrapper col-lg-6 col-md-6 col-lg-3">
                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer()">
                    ${answer.text}
                </button>
            </div>
        `;
        answersBlock += answerButton;
    });
    answerButtonsElement.innerHTML = answersBlock;
}

const selectAnswer = (e) => {
    const selectedButton = e.target;
    const correct = selectedButton.dataset.correct;
    setStatusClass(document.body, correct);
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct);
    })
}

function setStatusClass(element, correct) {
    clearStatusClass(element);
    if (correct) {
        element.classList.add('correct');
    } else {
        element.classList.add('wrong');
    }
}

function clearStatusClass(element) {
    element.classList.remove('correct');
    element.classList.remove('wrong');
}


const gameData = [
    {
        question: 'What is the smallest country in the world?',
        answer: [
            { text: 'Vatican City', correct: true },
            { text: 'Malta', correct: false },
            { text: 'Italy', correct: false },
            { text: 'Monaco', correct: false }
        ]
    },

【问题讨论】:

  • 什么不起作用?您是否使用浏览器中的开发工具进行了所有调试?你有错误吗?
  • 不要将答案结果存储到data-* 属性中。将它们存储在您的 gameData 中。
  • 请看How To Ask
  • 是的,这是一个错误:script.js:131 Uncaught TypeError: Cannot read properties of undefined (reading 'target') at selectAnswer (script.js:131:30) at HTMLButtonElement.onclick (index .html:1:1)

标签: javascript html css


【解决方案1】:

您必须在onclick 中将事件作为参数传递,因为您在 HTML 中使用该事件并直接调用它。

const answerButton = `
            <div class="answers-wrapper col-lg-6 col-md-6 col-lg-3">
                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer(event)">
                    ${answer.text}
                </button>
            </div>
        `;

并在selectAnswer 函数中将其作为event.target 获取。

function selectAnswer(event) {
  console.log("Button", event.target)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多