2014-01-30 34 views
0

我有一個裏面有一個p的div,它說'折它!'。當我點擊div時,p的文字變成'Expand it'。我怎樣才能做到這一點,當我第二次點擊div時,它會變回'摺疊'?JQuery在點擊時改變文本(也改回來)

HTML:

<div id="fold"> 
    <p id="fold_p">Fold it</p> 
</div> 

JQuery的:

<script> 
    $(document).ready(function() { 
    $("#fold").click(function() { 
     $("#fold_p").text("Expand it"); 
    }) 
    });     
</script> 

而且,是有可能使過渡褪色? 任何幫助是非常讚賞:)

+1

[jQuery的按鈕文字切換]的可能重複(HTTP://計算器.com/questions/13652835/button-text-toggle-in-jquery) – undefined

回答

2
$(document).ready(function() { 
    $("#fold").click(function() { 
     $("#fold_p").fadeOut(function() { 
      $("#fold_p").text(($("#fold_p").text() == 'Fold it') ? 'Expand it' : 'Fold it').fadeIn(); 
     }) 
    }) 
}); 

jsFiddle example

+0

哇,這個工程很棒。但是,我有沒有機會指定淡出時間? –

+0

當然,只需將持續時間作爲淡入淡出函數的第一個參數即可。請參閱http://jsfiddle.net/j08691/BdQU2/2/。例如:'$(「#fold_p」)。fadeOut(2000,function(){' – j08691

+0

您真棒! –

0
jQuery ("#fold") .click (function() { 
     if (jQuery (this).children ("#fold_p").text() == "Fold it") { 
       jQuery (this).children ("#fold_p").text("Expand It"); 
     } 
     else { 
      jQuery (this).children ("#fold_p").text("Fold it");   
     } 
    }); 

以上是對你的問題的示例代碼。

這裏是小提琴鏈接:http://jsfiddle.net/teZQA/

0

Fiddle Demo

$(document).ready(function() { 
    var fold = $("#fold"); 
    fold.cliked = 1;// set initial click value to 1 
    fold.click(function() { 
    //change text o base of even or odd 
     $("#fold_p").text((fold.cliked++ % 2 == 0) ? "Fold it" : "Expand it"); 
    }); 
}); 
0

試試這個:

<script> 
$(document).ready(function() { 
    $("#fold").click(function(){ 
    if($(this).hasClass("helperClass")){ 
    $(this).find("p").text("Expand it"); 

    }else{ 
     $(this).find("p").text("Fold it"); 
    } 
    $(this).toggleClass("helperClass"); 
    }); 
});     
</script>