【问题标题】:How to compare a text in an HTML element with a value in an array of objects?如何将 HTML 元素中的文本与对象数组中的值进行比较?
【发布时间】:2022-06-11 02:01:09
【问题描述】:

这是我的第一个 JavaScript 代码 - 它是一个测验应用程序。 我试图通过将用户选择的文本与正确答案文本进行比较来计算用户得分的正确答案数量,并且每次他们这样做时,userScore 变量都应该增加。然而,在这个过程中,它返回了最初定义的值,a.k.a 0

我有下面提到的整个代码

!!解决了!! 专注于 selectAnswer() 函数——答案就在那里

//select all the elements of the page

const startCard = document.getElementById('on-start');
const quizCard = document.getElementById('after-start');
const questionNumberElement = document.querySelector('.question-number');
// const timerBox = document.querySelector('.timer');
const questionElement = document.querySelector('.question');
const answersElement = document.getElementById('answers');
const answerElement = document.querySelectorAll('.answer');
const quitButton = document.querySelector('.quit');
const endCard = document.getElementById('the-end');
const scoreElement = document.querySelector('.score');
const messageElement = document.querySelector('.message');
const tryAgain = document.querySelector('.try-again');




let que_count = 0;
let userScore = 0;
// let timeValue = 10;

startCard.onclick = () => {
    //intro hides and quiz card shows
    startCard.classList.add('hide');
    quizCard.classList.remove('hide');
    //show all questions and answers
    // startTimer(10);
    showQuestion(0);
    //timer re-starts
}

// function startTimer(time) {
//     counter = setInterval(timer, 1000);
//     function timer() {
//         timerBox.textContent = time;
//         time--;
//         if (time < 9) {
//             let addZero = timerBox.textContent;
//             timerBox.textContent = '0' + addZero;
//         }
//         if (time < 0) {
//             clearInterval(counter);
//             // nextQuestion();
//         }
//     }
// }

tryAgain.onclick = () => {
    window.location.reload();
}

quitButton.onclick = () => {
    window.location.reload();
}

function showQuestion(index) {
    //question number changes
    let queNumber = 'Question ' + questions[index].numb;
    questionNumberElement.innerHTML = queNumber;

    //question changes
    let que = questions[index].question;
    questionElement.innerHTML = que;

    //answers change
    questions[index].answers.forEach(answer => {
        const button = document.createElement('button')
        button.innerText = answer.text
        button.classList.add('answer')
        //when answer is selected
        if (answer.correct) {
            button.dataset.correct = answer.correct
        }
        button.addEventListener('click', selectAnswer)
        // index++;
        answersElement.appendChild(button)
    })
}

function selectAnswer(answer) {
    let userAns = answer.target.innerText;
    let correctAns = questions[que_count].rightAnswer;
    if (userAns == correctAns) {
        userScore++;
    }
    resetState();
    if (que_count < questions.length - 1) {
        nextQuestion();
    }
    else {
        showResult();
    }
}

function showResult() {
    quizCard.classList.add('hide');
    startCard.classList.add('hide');
    endCard.classList.remove('hide');

    let score = ((userScore / questions.length) * 100);
    let score_message = 'You scored a ' + score + '%';
    scoreElement.innerText = score_message;

    if (score <= 40) {
        let msg = messages[5];
        messageElement.innerText = msg;
    }
    else if (score <= 50) {
        let msg = messages[4];
        messageElement.innerText = msg;
    }
    else if (score <= 60) {
        let msg = messages[3];
        messageElement.innerText = msg;
    }
    else if (score < 70) {
        let msg = messages[2];
        messageElement.innerText = msg;
    }
    else if (score < 80) {
        let msg = messages[1];
        messageElement.innerText = msg;
    }
    else {
        let msg = messages[0];
        messageElement.innerText = msg;
    }
}

function nextQuestion() {
    que_count++;
    showQuestion(que_count);
    // startTimer(timeValue);
}

function resetState() {
    // clearStatusClass(document.body)
    while (answersElement.firstChild) {
        answersElement.removeChild(answersElement.firstChild)
    }
}

const questions = [
    {
        numb: 1,
        question: 'When did Will Byers go missing',
        rightAnswer: 'November 6th, 1983',
        answers: [
            { text: 'November 6th, 1983' },
            { text: 'October 6th, 1983' },
            { text: 'November 9th, 1989' },
            { text: 'September 6th, 1983' }
        ]
    },
    {
        numb: 2,
        rightAnswer: 'Bob Newby',
        question: 'Who founded Hawkins Middle School AV Club',
        answers: [
            { text: 'Mr. Clarke' },
            { text: 'Bob Newby' },
            { text: 'Joyce Byers' },
            { text: 'Dustin Henderson' }
        ]
    },
    {
        numb: 3,
        rightAnswer: 'Cherry',
        question: 'What flavour slurpee does Alexei ask Hopper?',
        answers: [
            { text: 'Strawberry' },
            { text: 'Blueberry' },
            { text: 'Cherry' },
            { text: 'Mango' }
        ]
    },
    {
        numb: 4,
        rightAnswer: 'Mike Wheeler',
        question: '\'If anyone asks where I am, I\'ve left the country\'',
        answers: [
            { text: 'Erica Sinclair' },
            { text: 'Lucas Sinclair' },
            { text: 'Mike Wheeler' },
            { text: 'Jim Hopper' }
        ]
    }
]

const messages = [
    'Excellent job! You got way too much free time buddy',
    'Great score! You must love Steve a lot huh',
    'Good score, my man. I\'m sure we\'re both looking forward for s4',
    'You should rewatch!!',
    'You should rewatch!',
    'Okay... Get outta here'
]
    // { num: 1, message: 'Excellent' }, //90+
    // { num: 2, message: 'Great' }, //80+
    // { num: 3, message: 'Good' },
    // { num: 4, message: 'Alright' },
    // { num: 5, message: 'Poor' },
    // { num: 6, message: 'Very Poor' }

这是代码的 HTML 部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quiz</title>
    <link href="style.css" rel="stylesheet" />
</head>

<body>
    <div class="quiz-card">
        <div id="on-start">
            <div class="intro">How well do you know Stranger Things?</div>
            <button class="start" id="start-btn">Start</button>
        </div>

        <div id="after-start" class='hide'>
            <div class="question-timer" id='question'>
                <div class="question-number"></div>
                <div class="timer">0:00</div>
            </div>
            <div class="question">Which actor plays Steve Harrington?</div>
            <div class="answers" id="answers">
                <!-- <button class="answer">hi</button>
                <button class="answer">there</button>
                <button class="answer">sweety</button>
                <button class="answer">hehe</button> -->
            </div>
            <button class="quit">Quit</button>
        </div>
        <div id="the-end" class="hide">
            <h5 class="result">
                <div class="score"></div>
                <div class="message"></div>
            </h5>
            <button class="try-again">Try again</button>
        </div>
    </div>

    <script src="script-2.js"></script>
</body>

</html>

【问题讨论】:

    标签: javascript html increment


    【解决方案1】:

    写你的第一个 JavaScript 做得很好!

    我注意到的第一件事是,在您的 questions 数组中,在问题 2 中,您遇到了语法问题。在问题中,您在单词“What's”中使用了撇号,这告诉 JavaScript 它是字符串的结尾。您需要在它之前使用 \ 转义它,或者将字符串周围的引号更改为双引号 "

    我不知道这是否能解决问题,但这是第一步。

    第二步 - 您是否在控制台中遇到任何错误?

    接下来我要尝试的是:在您的selectAnswer 函数中,使用console.log() 打印出userAns == correctAns 的结果,看看它是否正确。它可能没有增加,因为它从未到达那条线,因为 userAnscorrectAns 永远不会匹配。

    我希望这能让您走上正确的道路,但如果没有,请同时发布您的 HTML,我会对其进行测试。

    【讨论】:

    • 第一个问题是因为我在 stackoverflow 上编辑了它 - 这是一个非常愚蠢的问题,没有注意到撇号。但是,我检查了第二个问题,看看它是否甚至通过了 if 语句,但事实并非如此。我已经在上面编辑了我的整个代码,以防您需要处理。
    • 哈哈没问题。感谢您分享 HTML。问题在于您的 selectAnswer 函数 - 您正在传递一个名为“answer”的参数,但我认为这不是您所期望的。它没有任何 textContent,因此当您将其与 rightAnswer 进行比较时,它总是错误的。
    • 感谢您的帮助 - 比较两者确实是个问题。我已经解决并附上了上面的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多