遍历数组

时间:2020-04-18 22:32:06

标签: javascript jquery loops iteration

我在遍历for循环以获取数组中的索引时遇到麻烦。触发事件处理程序后,它会直接转到最后一个索引,而不是转到下一个索引。

var elems = document.getElementsByClassName("question-container"); // returns a nodeList
var questionArray = jQuery.makeArray(elems);

nextButton.addEventListener('click', function () {
    for (var i = 0; i < questionArray.length; i++) {
        $(questionArray).hide();
        $(correct).hide();
        $(questionArray[i]).show();
    }
});

HTML是8个div,与此相同

<div class="question-container">

            <h2>How many rocketships do you see?</h2>
            <img class="small-img" src="img/rocket.png">
            <div>
                <button class="one" id="butt1" value="1">1</button>
                <button class="one" id="butt2" value="2">2</button>
                <button class="one" id="butt3" value="3">3</button>
                <button class="one" id="butt4" value="4">4</button>
                <button class="one" id="butt5" value="5">5</button>
            </div>

        </div>

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您有8个问题,但一次只能看到一个,当一个问题按下 next 按钮(代码中未显示)时,当前问题将被隐藏,而下一个问题将被隐藏。显示。

如果是这样,这是一个命题

/* CSS */

.question-container {
    display: none;
}

.question-container-visible {
    display: block;
}

/* JavaScript */

const questionArray = [...document.getElementsByClassName("question-container")]; // this is of type Array
let questionIndex = 0; // keep track of the question which must be shown

nextButton.addEventListener('click', evt => {
    questionIndex++; // show the next question
    showQuestion();
});

function showQuestion() {
    questionArray.forEach((question, index) => {
        // show only the question which has an index equal to questionIndex
        question.classList.toggle('question-container-visible', index === questionIndex);
    });
}

showQuestion(); // show the first question

如果我们假设第一个问题从一开始就具有question-container-visible类,那么JS代码可以简化为

const questionArray = [...document.getElementsByClassName("question-container")];
let questionIndex = 0;

nextButton.addEventListener('click', evt => {
    questionIndex++;
    questionArray.forEach((question, index) => {
        question.classList.toggle('question-container-visible', index === questionIndex);
    });
});