jQuery Toggle Text?

后端 未结 20 955
日久生厌
日久生厌 2020-12-02 05:52

How to toggle HTML text of an anchor tag using jQuery? I want an anchor that when clicked the text alternates between Show Background & Show Text

相关标签:
20条回答
  • 2020-12-02 06:19

    Why don't you just stack them ::

    $("#clickedItem").click(function(){
      $("#animatedItem").animate( // );
    }).toggle( // <--- you just stack the toggle function here ...
    function(){
      $(this).text( // );
    },
    function(){
      $(this).text( // );
    });
    
    0 讨论(0)
  • 2020-12-02 06:19
    $.fn.toggleText = function(a){
        var ab = a.split(/\s+/);
        return this.each(function(){
            this._txIdx = this._txIdx!=undefined ? ++this._txIdx : 0;
            this._txIdx = this._txIdx<ab.length ? this._txIdx : 0; 
            $(this).text(ab[this._txIdx]);
        }); 
    }; 
    $('div').toggleText("Hello Word");
    
    0 讨论(0)
  • 2020-12-02 06:23

    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 sue 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

    0 讨论(0)
  • 2020-12-02 06:23

    Nate-Wilkins's improved function:

    jQuery.fn.extend({
        toggleText: function (a, b) {
            var toggle = false, that = this;
            this.on('click', function () {
                that.text((toggle = !toggle) ? b : a);
            });
            return this;
        }
    });
    

    html:

    <button class="button-toggle-text">Hello World</button>
    

    using:

    $('.button-toggle-text').toggleText("Hello World", "Bye!");
    
    0 讨论(0)
  • 2020-12-02 06:23
    var jPlayPause = $("#play-pause");
    jPlayPause.text(jPlayPause.hasClass("playing") ? "play" : "pause");
    jPlayPause.toggleClass("playing");
    

    This is a piece of thought using jQuery's toggleClass() method.

    Suppose you have an element with id="play-pause" and you want to toggle the text between "play" and "pause".

    0 讨论(0)
  • 2020-12-02 06:25

    You can also toggleText by using toggleClass() as a thought ..

    .myclass::after {
     content: 'more';
    }
    .myclass.opened::after {
     content: 'less';
    }
    

    And then use

    $(myobject).toggleClass('opened');
    
    0 讨论(0)
提交回复
热议问题