循环在第一个时间间隔内被困住了

时间:2017-09-22 21:34:45

标签: javascript arrays function for-loop

我意识到你们中的一些人会在一秒内发现这一点,但由于某种原因,当使用onclick命令点击按钮时,我不能让循环循环多于初始循环。

{{1}}

任何帮助将不胜感激。我环顾四周但却找不到它,我确定它是因为它有如此明显的修复/愚蠢的错误:D

谢谢..

2 个答案:

答案 0 :(得分:3)

如果您想在每次点击按钮时显示新问题。您可以尝试以下方法:

//creat array with my questions
var qArray = ['What is the answer to the sum 1 + 1?', 'If I have two eggs and I drop one how many do I have left?', 'What are the three primary     colors?'];

//create variables
var counter = 0;
var theQuestions = document.getElementById('theQuestions');

//loop through array
function questFunc() {
    if (counter < qArray.length) {
        theQuestions.innerHTML = qArray[counter];
        counter++;
    }
};

答案 1 :(得分:1)

fo r循环按预期工作,第一个问题出现在这一行:theQuestions.innerHTML = qArray[i];。每当您更改innerHTML时,它都没有添加一个项目,它只是用新的值覆盖了以前的值,因此您可以尝试使用append()。第二个问题是在你的情况下使用for循环,这样你只需按一下按钮就可以遍历整个数组。您已经有counter变量来存储将在下一次按钮单击后使用的数组索引。可能是解释不是很好,但可以随意提出更多问题。

和一个片段:

//creat array with my questions
var qArray = ['What is the answer to the sum 1 + 1?', 'If I have two eggs and I drop one how many do I have left?', 'What are the three primary     colors?'];

//create variables
var counter = 0;
var theQuestions = document.getElementById('theQuestions');

//loop through array
function questFunc() {
    if (counter < qArray.length) {
      theQuestions.append(qArray[counter]);
      counter ++;
    }
};
<button onclick="questFunc()">Click</button>
<div id="theQuestions"></div>

以下是innerHTML

的工作原理

//creat array with my questions
var qArray = ['What is the answer to the sum 1 + 1?', 'If I have two eggs and I drop one how many do I have left?', 'What are the three primary     colors?'];

//create variables
var counter = 0;
var theQuestions = document.getElementById('theQuestions');

//loop through array
function questFunc() {
    if (counter < qArray.length) {
      theQuestions.innerHTML = qArray[counter];
      counter ++;
    }
};
<button onclick="questFunc()">Click</button>
<div id="theQuestions"></div>