点击按钮

时间:2017-04-21 12:29:56

标签: javascript php jquery html arrays

如何在每个按钮上点击每个数组元素的内部HTML?

https://jsfiddle.net/s0toedfh/2/

var fruits = ["Banana", "Orange", "Apple", "Mango"]; $("p").html(fruits[0]);

$( "button" ).click(function() { $("p").html(fruits[1]); });

3 个答案:

答案 0 :(得分:3)

试试这个,

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>

答案 1 :(得分:1)

您可以使用变量来计算点击发生的次数。

外部定义的变量可以初始化为0,每次点击时,它可以递增,并使用水果列表的长度执行modulo,以确保它始终保持在0-length_of_fruits之间

这是一个实现

var fruits = ["Banana", "Orange", "Apple", "Mango"];

$("p").html(fruits[0]);

var count = 0
$("button").click(function() {
  count = (count + 1) % fruits.length
  $("p").html(fruits[count]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<br>
<button>  click  </button>

答案 2 :(得分:0)

更简单的一个:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = 0;

$("button").click(function() {
  $("p").html(fruits[index%fruits.length]);
  index++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>&nbsp;</p>
<br>
<button>
click
</button>