关于问答游戏中的事件监听器

时间:2019-09-30 17:27:50

标签: javascript html addeventlistener

我的测验游戏有问题。我想知道是否需要事件监听器来刷新问题和4个选项的第一页。那会是什么样子?我正在使用json存储所有问题。

javascript,以及我在第一页中的选项和问题:

let question = document.getElementById("question").innerHTML = quiz.quests[0].question; let answer1 = document.getElementById("answer1").innerHTML = quiz.quests[0].answer[0].alt; let answer2 = document.getElementById("answer2").innerHTML = quiz.quests[0].answer[1].alt; let answer3 = document.getElementById("answer3").innerHTML = quiz.quests[0].answer[2].alt; let answer4 = document.getElementById("answer4").innerHTML = quiz.quests[0].answer[3].alt;

<div id="wrapper_questions">
<div class="background">
    <div class="grid">
        <div id="question">
            <h1></h1>
        </div>
        <hr style="margin-bottom: 20px">

        <div id="choices">
            <input type="checkbox" id="choice1"><span id="answer1"></span>
            <br>
            <input type="checkbox" id="choice2"><span id="answer2"></span>
            <br>
            <input type="checkbox" id="choice3"><span id="answer3"></span>
            <br>
            <input type="checkbox" id="choise4"><span id="answer4"></span>
        </div>
        <hr style="margin-bottom: 50px">

        <button onclick="nextQuestion()" >Next</button>
        <br>
        <footer>
                <p  id="progress">Question x of y.</p>
        </footer>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

这里是一个事件侦听器,它仅在选择一个选项时发出警报。也许这可以帮助您入门。

let choices = document.getElementById("choices");
choices.addEventListener('click', (event)=>
{
  console.log(event.target.id);

});
<div id="wrapper_questions">
<div class="background">
    <div class="grid">
        <div id="question">
            <h1></h1>
        </div>
        <hr style="margin-bottom: 20px">

        <div id="choices">
            <input type="radio" id="choice1" name="choiceForQuestion1"><span id="answer1">Answer 1</span>
            <br>
            <input type="radio" id="choice2" name="choiceForQuestion1"><span id="answer2">Answer 2</span>
            <br>
            <input type="radio" id="choice3" name="choiceForQuestion1"><span id="answer3">Answer 3</span>
            <br>
            <input type="radio" id="choise4" name="choiceForQuestion1"><span id="answer4">Answer 4</span>
        </div>
        <hr style="margin-bottom: 50px">

        <button onclick="nextQuestion()">Next</button>
        <br>
        <footer>
                <p  id="progress">Question x of y.</p>
        </footer>
    </div>
</div>

但是,如果选择是互斥的,我将使用radio而不是复选框。