【发布时间】:2020-11-14 12:35:22
【问题描述】:
问题是当我点击下一个按钮时,它会转到最后一个问题。我希望当按钮被点击时,循环一个一个地遍历所有问题。
var showquestion = document.querySelector('.content h2');
var nextbtn = document.getElementById('next');
var prevbtn = document.getElementById('prev');
//set questions in array
var questions = [
"hell I am the first question",
"hell I am the second question",
"hell I am the thirs question",
"hell I am the fourth question"
]
//next question function
nextbtn.addEventListener('click', nextquestion);
function nextquestion() {
var random = Math.floor()
for (var i = 0; i < questions.length; i++) {
showquestion.textContent = questions[i];
}
}
<div class="container">
<div class="content">
<h2>Hello the question will go here</h2>
<input type="button" name="b1" id="next" value="Next">
<input type="button" name="b2" id="prev" value="Previous">
</div>
</div>
【问题讨论】:
-
你做了什么?当您单击下一步时,您正在遍历所有问题,并且不使用随机变量!此外,您需要保存先前随机问题的状态,即索引!只需维护一个变量 i 并继续以问题数组长度的 mod 递增,或者如果您选择随机方法,则保存数组的前一个索引。
标签: javascript html css arrays for-loop