【问题标题】:javascript onclick from array in order按顺序从数组中单击javascript
【发布时间】:2014-07-02 17:05:53
【问题描述】:

我正在制作一份“是/否”问卷,一次回答一个问题,并且在问题底部有一个“下一步”按钮。

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

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

【问题讨论】:

  • 不改变HTML,而是将HTML中的所有HTML放在文档中,放在不同的DIV中。然后通过更改style.display 隐藏和显示它们。

标签: javascript html arrays function onclick


【解决方案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] = "";

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多