jQuery Toggle Text?

后端 未结 20 987
日久生厌
日久生厌 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:29

    The most beautiful answer is... Extend jQuery with this function...

    $.fn.extend({
        toggleText: function(a, b){
            return this.text(this.text() == b ? a : b);
        }
    });
    

    HTML:

    
    

    Use:

    $(".example").toggleText('Initial', 'Secondary');
    

    I've used the logic ( x == b ? a : b ) in the case that the initial HTML text is slightly different (an extra space, period, etc...) so you'll never get a duplicate showing of the intended initial value

    (Also why I purposely left spaces in the HTML example ;-)

    Another possibility for HTML toggle use brought to my attention by Meules [below] is:

    $.fn.extend({
            toggleHtml: function(a, b){
                return this.html(this.html() == b ? a : b);
            }
        });
    

    HTML:

    John Doe was an unknown.

    Use:

    $("readmore_john_doe").click($.toggleHtml(
        'Read More...', 
        'Until they found his real name was Doe John.')
    );
    

    (or something like this)

提交回复
热议问题