[英]Change div text with jQuery Toggle
使用slideToggle
,如何更改文本關閉/顯示? 我做了一個簡單的,但無法將文本更改回來。
這是我做的:
$(document).ready(function(){ $('.open').click(function(){ $('.showpanel').slideToggle('slow'); $(this).text('close'); }); $('.open2').click(function(){ $('.showpanel2').slideToggle('slow'); $(this).text('close'); }); });
body{ font-size:20px; } #box{ border:2px solid #000; width:500px; min-height:300px; } .open,.open2 { width:450px; height:50px; background:blue; margin:5px auto 0 auto; color:#fff; } .showpanel,.showpanel2{ width:450px; height:300px; margin:0 auto 10px auto; background:red; display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box"> <div class="open">Show</div> <div class="showpanel">This is content</div> <div class="open2">Show</div> <div class="showpanel2">This is content</div> </div>
您可以使用is()
斷言方法來檢查面板在動畫的回調中是打開還是關閉,並相應地設置文本 - http://jsfiddle.net/9EFNK/7/
$('.open').click(function(){
var link = $(this);
$('.showpanel').slideToggle('slow', function() {
if ($(this).is(':visible')) {
link.text('close');
} else {
link.text('open');
}
});
});
只需添加一個簡單的if語句來測試文本就像這樣
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
if($(this).text() == 'close'){
$(this).text('Show');
} else {
$(this).text('close');
}
});
喜歡這個DEMO
不是最漂亮的方法,但它只在一個語句中完成工作。
$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');
這是一個更新版本http://jsfiddle.net/9EFNK/1/
您可以在關閉/打開時簡單地切換類,對該類執行檢查並相應地更改包含的文本
if( $(this).hasClass('active') )
$(this).text('open');
else
$(this).text('Show');
$(this).toggleClass('active');
使用.toggle()
這是工作演示
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
}).toggle(function() {
$(this).text('Hide');
}, function() {
$(this).text('Show');
});
檢查這可能是用戶問題解決小提琴
試試這個演示
$(document).ready(function(){
$('.open').toggle(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel').slideToggle('slow');
$(this).text('Show');
});
$('.open2').toggle(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel2').slideToggle('slow');
$(this).text('Show');
});
});
用這個
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
這是你如何使用它
jQuery.fn.toggleText = function() { var altText = this.data("alt-text"); if (altText) { this.data("alt-text", this.html()); this.html(altText); } }; $('[data-toggle="offcanvas"]').click(function () { $(this).toggleText(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <button data-toggle="offcanvas" data-alt-text="Close">Open</button>
你甚至可以使用HTML,只要它的html編碼正確
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.