Change div text with jQuery Toggle

2019-03-09 19:01发布

When using slideToggle, how to change the Text close/show? I did a simple one, but cannot get the text change back.

Here is what I did:

$(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>

http://jsfiddle.net/9EFNK/

8条回答
Evening l夕情丶
2楼-- · 2019-03-09 19:37

You can use the is() assertion method to check whether the panel is open or closed in the animation's callback and set the text accordingly - 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');                
        }        
    });       
});
查看更多
爷的心禁止访问
3楼-- · 2019-03-09 19:39

Not the prettiest of methods, but it does the job in a single statement.

$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');
查看更多
登录 后发表回答