可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
$(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.
回答1:
$(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:
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:
<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
(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:
<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)
回答3:
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".
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!
回答4:
Improving and Simplifying @Nate's answer:
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');
回答5:
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.
JSFiddle: http://jsfiddle.net/NKuhV/
回答6:
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( // );
});
回答7:
var el = $('#someSelector');
el.text(el.text() == 'view more' ? 'view less' : 'view more');
回答8:
Use html() to toggle HTML content.
Similar to fflyer05's code:
$.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/
回答9:
I've written my own little extension for toggleText. It may come in handy.
Fiddle: https://jsfiddle.net/b5u14L5o/
jQuery Extension:
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 -------
回答10:
Modifying my answer from your other question, I would do this:
$(function() {
$("#show-background").click(function () {
var c = $("#content-area");
var o = (c.css('opacity') == 0) ? 1 : 0;
var t = (o==1) ? 'Show Background' : 'Show Text';
c.animate({opacity: o}, 'slow');
$(this).text(t);
});
});
回答11:
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
回答12:
In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:
$.fn.extend({
toggleText: function (a, b){
if (this.text() == a){ this.text(b); }
else { this.text(a) }
}
);
You could use it this way:
$(document).on('click', '.toggle-details', function(e){
e.preventDefault();
//other things happening
$(this).toggleText("Show Details", "Hide Details");
});
回答13:
$.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");
回答14:
<h2 id="changeText" class="mainText"> Main Text </h2>
(function() {
var mainText = $('.mainText').text(),
altText = 'Alt Text';
$('#changeText').on('click', function(){
$(this).toggleClass('altText');
$('.mainText').text(mainText);
$('.altText').text(altText);
});
})();
回答15:
Perhaps I'm oversimplifying the problem, but this is what I use.
$.fn.extend({
toggleText: function(a, b) {
$.trim(this.html()) == a ? this.html(b) : this.html(a);
}
});
回答16:
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!");
回答17:
this is not the very clean and smart way but its very easy to understand and use somtimes - its like odd and even - boolean like:
var moreOrLess = 2;
$('.Btn').on('click',function(){
if(moreOrLess % 2 == 0){
$(this).text('text1');
moreOrLess ++ ;
}else{
$(this).text('more');
moreOrLess ++ ;
}
});
回答18:
Why not keep track of the state of through a class without CSS rules on the clickable anchor itself
$(function() {
$("#show-background").click(function () {
$("#content-area").animate({opacity: 'toggle'}, 'slow');
$("#show-background").toggleClass("clicked");
if ( $("#show-background").hasClass("clicked") ) {
$(this).text("Show Text");
}
else {
$(this).text("Show Background");
}
});
});
回答19:
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".