Change div text with jQuery Toggle

两盒软妹~` 提交于 2019-12-02 18:07:16

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

Just add a simple if statement to test the text like so

$('.open').click(function(){

       $('.showpanel').slideToggle('slow');
       if($(this).text() == 'close'){
           $(this).text('Show');
       } else {
           $(this).text('close');
       }
});

Like this DEMO

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

$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');

Here's an updated version http://jsfiddle.net/9EFNK/1/

You can simply toggle a class on close/open, perform a check for that class and change the contained text accordingly

if( $(this).hasClass('active') )
  $(this).text('open');
else
  $(this).text('Show');

$(this).toggleClass('active');

Use .toggle()

Here is Working Demo

$('.open').click(function(){    
        $('.showpanel').slideToggle('slow');                  
    }).toggle(function() {
            $(this).text('Hide');
        }, function() {
            $(this).text('Show');
        });

check this may be user question is solve Fiddle

try this demo

$(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');
    });   
});​

Use this

jQuery.fn.toggleText = function() {
    var altText = this.data("alt-text");
    if (altText) {
        this.data("alt-text", this.html());
        this.html(altText);
    }
};

Here is how you use it

 
   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>

You can even use html provided it's html encoded properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!