jQuery - Toggle .html text?

2020-06-04 03:07发布

Why won't this work?

http://jsfiddle.net/PdwJ6/

HTML

<a href="#" id="showMore">Before</a>

JS

$('#showMore').click(function() {

$(this).toggle(
function () {
    $(this).html('<a href="#">After</a>');},
function () {
    $(this).html('<a href="#">Before</a>');
});
});

标签: jquery
7条回答
欢心
2楼-- · 2020-06-04 03:22
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');
查看更多
孤傲高冷的网名
3楼-- · 2020-06-04 03:25

You are binding a click to the <a/> and than inside of that you are binding a toggle() to it.

If you simply want to toggle you can leave off the click().

$('#showMore').toggle(
    function() {
       $(this).html('<a href="#">After</a>');
    }, 
    function() {
       $(this).html('<a href="#">Before</a>');
});

With that being said you are placing an <a/> inside of another <a/> Is that really what you want? Or you you just want to replace the .text()? .text("Before")

Jsfiddle example of toggle()

查看更多
倾城 Initia
4楼-- · 2020-06-04 03:26

Blender has the appropriate answer, but we can also generalize your question into a simple jQuery plugin:

$.fn.toggleText = function(t1, t2){
  if (this.text() == t1) this.text(t2);
  else                   this.text(t1);
  return this;
};

Your code would then look like:

$('#showMore').click(function(){
  $(this).toggleText('Before', 'After');
})
查看更多
男人必须洒脱
5楼-- · 2020-06-04 03:32

because you are nesting a <a> inside another, resulting in something like <a href="#" id="#showMore"><a href="">After</a></a>

You should just use $(this).text('After') and same with Before

I guess you wanted to use replaceWith() which is not very efficient in this situation because only the text changes.

++ the toggle bug spotted in the other answers. Kudos to them ;-)

查看更多
乱世女痞
6楼-- · 2020-06-04 03:39

This is a reduced / "more compact" version of the same answer here: "A simple solution for toggling after a click".

$('#showMore').on('click', function(){
    $(this).html($(this).html() == 'after' ? 'before' : 'after');
});

Of course this needs jQuery plugin for it to work.

查看更多
ゆ 、 Hurt°
7楼-- · 2020-06-04 03:42

A simple solution for toggling after a click:

$('#showMore').on('click', function(){
    $(this).html() == "after" ? $(this).html('before') : $(this).html('after');
});
查看更多
登录 后发表回答