如何创建一个循环或函数,以便在每次单击时显示新的数组索引。我尝试使用for循环,但我只获得第一个值,然后当我点击它时,它会跳转到最后一个值。
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
function textForward (){
arrow.addEventListener('click', function(){
var arr = [
'a','b','c','d'
]
for (var i = 0; i < arr.length; i++)
para.innerHTML = arr[i]
});
}
每次单击一个按钮,上面需要按顺序显示该数组的下一个值。 (例如,数组将从a开始,然后当用户点击它时,将转到b,然后在下一次单击c,依此类推)。
答案 0 :(得分:1)
想出来,我觉得因为没有把它弄清楚而感到愚蠢......这是更新后的代码
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
let counter = 0;
function textForward (){
var arr = [
'How are you?',
'Are you Ready to play the Game',
'Here is how it works',
'you have three hints to guess what I am thinking',
'Guess wrong and you are out',
'simple..let the games begin'
]
para.innerHTML = arr[counter];
counter ++;
}
textForward();
答案 1 :(得分:0)
您需要一个全局计数器来跟踪当前索引。像这样的东西
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
// The current index
var index = 0;
var arr = ['a','b','c','d'];
arrow.addEventListener('click', function(){
para.innerHTML = arr[index];
if(index < arr.length - 1) index++;
});