Before Js $('#sho...">

JQuery - Toggle .html text?

Why is this not working?

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>'); }); }); 
+3
source share
7 answers

Not sure with JsFiddle.net, but I can not post a demo.

You insert two functions inside each other ( .click() and .toggle() ), and .toggle() handles click , so this can cause a conflict. Also use text() instead of html() :

HTML

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

Javascript

 $('#showMore').toggle(function() { $(this).text('Before'); }, function() { $(this).text('After'); }); 
+14
source

The blender has a corresponding 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; }; 

Then your code will look like this:

 $('#showMore').click(function(){ $(this).toggleText('Before', 'After'); }) 
+17
source

A simple solution to switch after a click:

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

You bind click to <a/> , not inside the fact that you bind toggle() to it.

If you just want to switch, you can leave click() .

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

With that said, you put <a/> inside another <a/> . Is this really what you want? Or do you just want to replace .text() ? .text("Before")

Jsfiddle toggle() example

+3
source

because you insert <a> inside another, which leads to something like <a href="#" id="#showMore"><a href="">After</a></a>

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

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

++ switching error in other answers. Kudos to them; -)

+1
source

This is a shortened version with a more compact version of the same answer: "A simple solution to switch after a click . "

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

Of course, this requires a jQuery plugin to work.

+1
source
 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'); 
0
source

Source: https://habr.com/ru/post/1480713/


All Articles