[英]Jquery: changing text inside a button when toggle 'show'
我創建了一個切換按鈕來顯示和隱藏div,但是我希望在#content div上切換“顯示”時,按鈕內的文本從“顯示內容”變為“隱藏內容”。我仍在學習jQuery,這讓我有點煩惱,不勝感激!
編輯 :我發現,因為我在一個頁面上有很多帖子,並且在所有帖子中都重復了該代碼,當我單擊按鈕以在一個帖子上顯示內容時,它會在所有帖子上顯示內容。 如何補救?
HTML
<div class="post-content">
<button id='content-button'>Show Content</button>
<div id='content'>Hello World</div>
</div>
CSS #content {display:none; }
JQUERY
jQuery(document).ready(function(){
jQuery('#content-button').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
你可以這樣
jQuery(document).ready(function() {
jQuery('#content-button').live('click', function(event) {
$('#content').is(":visible") ? $(this).text("Show Content") : $(this).text("Hide Content");
jQuery('#content').toggle();
});
});
使用is(":visible")
檢查div的可見性,然后更改文本
編輯
jQuery('#content-button').live('click', function(event) {
$(this).next().is(":visible") ? $(this).text("Show Content") : $(this).text("Hide Content");
$(this).next().toggle();
});
您可以使用變量來保留單擊按鈕時的時間並更改文本:
jQuery(document).ready(function () {
var i = 0;
jQuery('#content-button').live('click', function (event) {
jQuery('#content').toggle('show');
if (i == 0) {
$(this).text("Hide Content");
i = 1;
} else {
$(this).text("Show Content");
i = 0;
}
});
});
我會簡單地編寫代碼(對幻燈片效果感到抱歉,但也許您對此也有興趣):
JQuery('#content-button').live('click', function(event) {
JQuery("#content").slideToggle("slow",function(){
if (JQuery("#content").css("display")=="none"){
JQuery(this).text("Show Content");
} else {
JQuery(this).text("Hide Content");
}
});
});
jQuery(document).ready(function(){
jQuery('#content-button').live('click', function(event) {
if(jQuery('#content').is(":hidden")){
jQuery(this).text("Hide Content");
jQuery('#content').show();
}
else{
jQuery(this).text("Show Content");
jQuery('#content').hide();
}
});
});
使用.text
更改按鈕的文本
jQuery(document).ready(function(){
jQuery('#content-button').live('click', function(event) {
jQuery('#content').toggle('show');
////////////////////////////code to change text
if($('#content-button').text()=="Show Content")
{
$('#content-button').text('hide content');
}
else
{
$('#content-button').text('show content');
}
////////////////////////////
});});
嘗試
jQuery(document).ready(function () {
jQuery('#content-button').live('click', function (event) {
jQuery('#content').toggle('show', function () {
if ($(this).is(":visible")) {
$('#content-button').text("Show Content");
} else {
$('#content-button').text("Hide Content");
}
});
});
});
大多數答案在這里是相似的。
為什么不創新並在此處添加自定義功能。
$.fn.toggleText = function(t1, t2){
if (this.text() == t1) this.text(t2);
else this.text(t1);
return this;
};
然后只需編輯您的代碼即可使用該功能。 因此,您可以在代碼的其他任何地方使用此功能。 簡化事情。
jQuery(document).ready(function(){
jQuery('#content-button').live('click', function(event) {
$(event.target).toggleText('Show Content', 'Hide Content'); //Add this line
jQuery('#content').toggle('show');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.