每次单击按钮时如何更改数组中的文本?所以我有:
<div class="buttons">
<a href="#" class="btn">Button 1</a>
<a href="#" class="btn">Button 2</a>
<a href="#" class="btn">Button 3</a>
</div>
<div class="text"></text>
我有数组:
var arr = ['First', 'Second', 'Third.'];
$(".btn").on('click', function (e) {
$(".text").text(arr[0]);
});
如何点击这些'.btn',它会遍历数组并淡入新文本?
答案 0 :(得分:1)
试试这个:
var arr = ['First', 'Second', 'Third.'];
var cnt = 0;
$(".btn").on('click', function (e) {
//alert(arr[cnt]);
$(".text").hide();
$(".text").text(arr[cnt]).fadeIn(1500);
cnt++;
if (cnt > 2) cnt = 0;
});
答案 1 :(得分:1)
$(".btn").each(function (index) {
$(this).click(function () {
$(".text").text(arr[index]);
});
});
答案 2 :(得分:0)
你应该像这样定义一个变量'i':
var i = 0;
var arr = ['First', 'Second', 'Third.'];
$(".btn").on('click', function (e) {
$(".text").text(arr[i]);
if (i < 2) i += 1;
else i = 0;
});
答案 3 :(得分:0)
试试这个:
<div class="buttons">
<a href="#" class="btn" index="0">Button 1</a>
<a href="#" class="btn" index="1">Button 2</a>
<a href="#" class="btn" index="2">Button 3</a>
</div>
<div class="text"></text>
var arr = ['First', 'Second', 'Third.'];
$(".btn").on('click', function (e) {
var index = $(this).attr("index");
$(".text").text(arr[index]);
});