无法访问数组javascript的下一个元素

时间:2016-08-01 07:57:32

标签: javascript html

我是JS新手,我试图使用onclick函数访问数组的下一个元素,但没有运气。



var i, len;
        
    function quiz() {
    var quiz_questions = [
    "who is the founder of facebook?",
    "who is the founder of google?"
    ];
            
    len = quiz_questions.length;

    for(i = 0; i < len; i++) {
    document.getElementById("demo").innerHTML = quiz_questions[i];
    }
}
&#13;
<button onclick="quiz();">Click</button>
<p id="demo"></p>
&#13;
&#13;
&#13;

任何人都可以解释我在这里做错了什么。

3 个答案:

答案 0 :(得分:0)

您的问题是,每次点击都会迭代每个问题。只需删除for循环并在设置问题后输入i ++。也许检查,如果我小于它之前的数组长度,那不是一个坏主意。

&#13;
&#13;
var i, len;
i = 0;
        
    function quiz() {
    var quiz_questions = [
    "who is the founder of facebook?",
    "who is the founder of google?"
    ];
            
    len = quiz_questions.length;

    document.getElementById("demo").innerHTML = quiz_questions[i];
    i++;
    if(i>=len){
      i=0;
    }
}
&#13;
<button onclick="quiz();">Click</button>
<p id="demo"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在您的javascript中进行更改,如:

var quiz_questions = [
"who is the founder of facebook?",
"who is the founder of google?"
];

var counter = 0;

function quiz() 
{
counter++;
document.getElementById("demo").innerHTML = quiz_questions[counter-1];
}

答案 2 :(得分:0)

此语句将继续覆盖demo div的值

document.getElementById("demo").innerHTML = quiz_questions[i];

相反,您需要将问题附加到变量,然后将其添加到div。这样两个问题都将被添加到div

var i, len;

function quiz() {
var quiz_questions = [
"who is the founder of facebook?",
"who is the founder of google?"
];

len = quiz_questions.length;
var htmlContent = "";
for(i = 0; i < len; i++) {
    htmlContent = htmlContent + quiz_questions[i] + "<br>";
}
    document.getElementById("demo").innerHTML = htmlContent;
}