Javascript按顺序从数组中点击

javascript onclick from array in order

本文关键字:数组 顺序 Javascript      更新时间:2023-09-26

我正在做一个是/否问卷,一次一个问题,在问题的底部有一个'下一步'按钮。

我希望Next按钮在每次单击时循环到数组中的下一个问题。我该怎么做呢?

 <button class="btn btn-large btn-block btn-primary" type="button"   onclick="nextQuestion()">Next</button>
    function nextQuestion(){
        document.getElementById("questionArea").innerHTML = ???,
}
var questionSet = new Array();
    questionSet[0] = "";
    questionSet[1] = "";  
    questionSet[2] = "";
    questionSet[3] = "";

只需添加var整数索引并在点击下一步时增加它

 <button class="btn btn-large btn-block btn-primary" type="button"onclick="nextQuestion()">Next</button>
var index_question = 0;
function nextQuestion(){
    document.getElementById("questionArea").innerHTML = questionSet[index_question];
    index_question ++;
}
var questionSet = new Array();
questionSet[0] = "";
questionSet[1] = "";  
questionSet[2] = "";
questionSet[3] = "";

您可以在保存索引的按钮上放置一个data-*属性,然后在click处理程序中获取该属性并在需要时进行递增。

<button class="btn btn-large btn-block btn-primary" 
        data-question="0" type="button"  
        onclick="nextQuestion(this)">Next</button>
function nextQuestion(btn){
    var index = (+btn.getAttribute("data-question"))+1;
    document.getElementById("questionArea").innerHTML = questionSet[index];
    btn.setAttribute("data-question",index);
}
var questionSet = new Array();
    questionSet[0] = "";
    questionSet[1] = "";  
    questionSet[2] = "";
    questionSet[3] = "";

当然你还需要检查以确保没有超出数组边界

您可以创建一个全局变量,并为每次单击增加值:

var questionCount = 0;
function nextQuestion(){
questionCount++;
document.getElementById("questionArea").innerHTML = questionSet[questionCount];
}