jQuery 切换文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2155453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:53:28  来源:igfitidea点击:

jQuery Toggle Text?

jquerytoggle

提问by mtwallet

Does anybody know how to toggle text the html text of an anchor tag using jQuery. I want an anchor that when clicked the text alternates between "Show Background" & "Show Text" as well as fading in & out another div. This was my best guess:

有谁知道如何使用 jQuery 切换文本和锚标记的 html 文本。我想要一个锚点,当单击文本在“显示背景”和“显示文本”之间交替以及淡入和淡出另一个 div 时。这是我最好的猜测:

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    $("#show-background").toggle(function (){
        $(this).text("Show Background")
        .stop();
    }, function(){
        $(this).text("Show Text")
        .stop();
    });
});

Thanks in advance.

提前致谢。

采纳答案by mtwallet

Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".

对不起是我的问题!这是不同步的,但这是因为我的 HTML 文本方式错误。在第一次单击时,我希望 div 淡出,文本显示“显示文本”。

Will check more thoroughly next time before I ask!

在我问之前,下次会检查得更彻底!

My code is now:

我的代码现在是:

$(function() {
  $("#show-background").toggle(function (){
    $("#content-area").animate({opacity: '0'}, 'slow')
    $("#show-background").text("Show Text")
      .stop();
  }, function(){
    $("#content-area").animate({opacity: '1'}, 'slow')
    $("#show-background").text("Show Background")
      .stop();
  });
});

Thanks again for the help!

再次感谢您的帮助!

回答by Kyle Butt

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    var text = $('#show-background').text();
    $('#show-background').text(
        text == "Show Background" ? "Show Text" : "Show Background");
});

Toggle hides or shows elements. You could achieve the same effect using toggle by having 2 links and toggling them when either is clicked.

切换隐藏或显示元素。您可以使用切换实现相同的效果,方法是拥有 2 个链接并在单击其中一个时切换它们。

回答by JxAxMxIxN

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

最好的答案是……用这个函数扩展jQuery……

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

HTML:

HTML:

<button class="example"> Initial </button>

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

在初始 HTML 文本略有不同(额外的空格、句点等...)的情况下,我使用了逻辑 ( x == b ? a : b ),因此您永远不会重复显示预期初始值

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

(也是为什么我故意在 HTML 示例中留下空格;-)

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

Meules [下面] 引起我注意的 HTML 切换使用的另一种可能性是:

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

HTML:

HTML:

<div>John Doe was an unknown.<button id='readmore_john_doe'> Read More... </button></div>

Use:

用:

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

(or something like this)

(或类似的东西)

回答by Diego Favero

Improving and Simplifying @Nate's answer:

改进和简化@Nate 的回答:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

用于:

$("#YourElementId").toggleText('After', 'Before');

回答by Nate-Wilkins

jQuery.fn.extend({
        toggleText: function (a, b){
            var isClicked = false;
            var that = this;
            this.click(function (){
                if (isClicked) { that.text(a); isClicked = false; }
                else { that.text(b); isClicked = true; }
            });
            return this;
        }
    });

$('#someElement').toggleText("hello", "goodbye");

Extension for JQuery that only does toggling of text.

仅切换文本的 JQuery 扩展。

JSFiddle: http://jsfiddle.net/NKuhV/

JSFiddle:http: //jsfiddle.net/NKuhV/

回答by Judson Terrell

var el  = $('#someSelector');    
el.text(el.text() == 'view more' ? 'view less' : 'view more');

回答by Eugene Koekemoer

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( // );
});

回答by Tomasz Majerski

Use html()to toggle HTML content. Similar to fflyer05's code:

使用html()切换 HTML 内容。类似于fflyer05的代码:

$.fn.extend({
    toggleText:function(a,b){
        if(this.html()==a){this.html(b)}
        else{this.html(a)}
    }
});

Usage:

用法:

<a href="#" onclick='$(this).toggleText("<strong>I got toggled!</strong>","<u>Toggle me again!</u>")'><i>Toggle me!</i></a>

Fiddle: http://jsfiddle.net/DmppM/

小提琴:http: //jsfiddle.net/DmppM/

回答by firstandlastpost

I've written my own little extension for toggleText. It may come in handy.

我已经为 toggleText 编写了我自己的小扩展。它可能会派上用场。

Fiddle: https://jsfiddle.net/b5u14L5o/

小提琴:https: //jsfiddle.net/b5u14L5o/

jQuery Extension:

jQuery 扩展:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
                                                    : $(this).text(stateOne);
        });  
    }
});

Usage:

用法:

...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------

//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------

//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------

//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------

回答by aWebDeveloper

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

您甚至可以使用 html,前提是它的 html 编码正确