<!DOCTYPE html>
<html>
<body>
<p>The best way to loop through an array is using a standard forloop:</p>
<label id="lab"/>
<button onclick="myfunc()">ok</button>
<script>
function myfunc() {
fru = ["Banana", "Orange", "Apple", "Mango"];
for (i = 0; i < fru.length; i++) {
document.getElementById("lab").innerHTML = fru[i];
}
}
</script>
</body>
</html>
我想在点击按钮时显示标签。我在数组中存储了5个值。单击按钮时,如何逐个显示这些数组值 ?
如果我点击一次,它会显示第一个标签,在我第二次点击时会显示第二个标签。
答案 0 :(得分:0)
您必须在function
之外放置一个varibale。可能是array
或counter variable
。这取决于你。一种方法是使用splice
缩小array
上的click
并输出第一个值。
var fru = ["Banana", "Orange", "Apple", "Mango"];
function myfunc() {
document.getElementById("lab").innerHTML += fru.splice(0, 1);
}
&#13;
<label id="lab" />
<button onclick="myfunc()">ok</button>
&#13;
答案 1 :(得分:0)
<强> HTML 强>
<p>The best way to loop through an array is using a standard forloop:</p>
<label id="lab"></label>
<button onclick="myfunc()">ok</button>
<强> JAVASCRIPT 强>
var counter=0;
function myfunc() {
fru = ["Banana", "Orange", "Apple", "Mango"];
var _innerString = '';
if(fru.length>counter){
_innerString = fru[counter]+('<br>');
counter++;
}else{
counter=0;
alert("Array Reset");
}
document.getElementById("lab").innerHTML =_innerString;
}
答案 2 :(得分:-1)
使用全局变量作为计数器来存储点击次数,并将此计数器值作为索引提供给数组以显示元素。当您单击
时,这将逐个显示值<script>
var counter=0;
function myfunc(){
fru = ["Banana", "Orange", "Apple", "Mango"];
if(counter == fru.length)
counter = 0; //reset index once end of array is reached
document.getElementById("lab").innerHTML = fru[counter];
counter++;
}
</script>