【问题标题】:How do I select the next item in an array when a user clicks on a button?当用户单击按钮时,如何选择数组中的下一个项目?
【发布时间】:2022-01-14 19:13:55
【问题描述】:

我正在使用 4 个按钮来回答问题(我总共有 6 个问题)。

如何从我的数组中获取下一组问题?它看起来像这样:

var questions = [{
       question: "the question!".
       answer1: "choice1",
       answer2: "choice2",
       answer3: "choice3",
       answer4: "choice4",
       correct: "choice3",

}}

【问题讨论】:

  • 您的数组定义中有一个语法错误(}} 在末尾而不是}]),并且您的数组仅包含一项。请提供有关您如何显示问题以及您当前如何尝试选择下一个问题的更多详细信息。

标签: javascript arrays


【解决方案1】:

只需跟踪数组中的当前索引,当他们单击时,增加索引。然后我只需要一个render 方法,它将索引作为参数。比如:

const questions = [{
       question: "the question!",
       answer1: "choice1",
       answer2: "choice2",
       answer3: "choice3",
       answer4: "choice4",
       correct: "choice3"

}, {
       question: "the next question!",
       answer1: "A",
       answer2: "B",
       answer3: "C",
       answer4: "D",
       correct: "C"
}];

var currentQuestionIndex = 0;

const c = document.getElementById('content');

const render = (idx) => {
    const q = questions[idx];
    c.innerHTML = `<strong>${q.question}</strong>
        <p><label><input name="q" type="radio"/>${q.answer1}</label>
        <p><label><input name="q" type="radio"/>${q.answer2}</label>
        <p><label><input name="q" type="radio"/>${q.answer3}</label>
        <p><label><input name="q" type="radio"/>${q.answer4}</label>
    `;
}

render(currentQuestionIndex);

document.getElementById('btn').addEventListener('click', () => {
    currentQuestionIndex = (currentQuestionIndex + 1) % questions.length;
    render(currentQuestionIndex);
});
<div id="content"></div>

<button id="btn">Next</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多