按顺序从数组中点击javascript

时间:2014-07-02 17:05:54

标签: javascript html arrays function onclick

我正在制作一个YES / NO问卷,一次只提出一个问题并且有一个' Next'问题底部的按钮。

我想让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] = "";

3 个答案:

答案 0 :(得分:1)

只需添加一个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] = "";

答案 1 :(得分:0)

您可以在保存索引的按钮上放置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] = "";

当然,您必须进行检查以确保不会超出数组范围

答案 2 :(得分:0)

您可以创建全局变量并增加每次点击的值:

var questionCount = 0;

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