如何在每次单击按钮时使用每个数组元素循环内部HTML?
https://jsfiddle.net/s0toedfh/2/
var fruits = ["Banana", "Orange", "Apple", "Mango"]; $("p").html(fruits[0]);
$( "button" ).click(function() { $("p").html(fruits[1]); });
最佳答案
尝试这个,
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index=0;
$( "button" ).click(function() {
$("p").html(fruits[index]);
index++;
if(index>=fruits.length)index=0;
});
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = 0;
$("button").click(function() {
$("p").html(fruits[index]);
index++;
if (index >= fruits.length) index = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
</p>
<br>
<button>
click
</button>
或者,您可以尝试
var fruits = ["Banana", "Orange", "Apple", "Mango"],
index = 0,
totalFruits=fruits.length;
$("button").click(function() {
$("p").html(fruits[index++ % totalFruits]); // increment and get index
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
</p>
<br>
<button>
click
</button>