2013-08-29 29 views
0

每次單擊按鈕時如何更改數組中的文本?所以,我有:使用jQuery多次更改文本

<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」,它會循環的點擊淡入新的文字?

回答

1

試試這個:

working jsFiddle here

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; 
}); 
0

你應該定義一個變量 '我' 是這樣的:

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; 
}); 
+0

'.fadeIn('slow',function(){ //動畫完成 });'他提到一個淡入,soooo這裏你去 –

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]); 
}); 
1
$(".btn").each(function (index) { 
    $(this).click(function() { 
     $(".text").text(arr[index]); 
    }); 
});