jQuery – 切换.html文本?
为什么这不起作用?
http://jsfiddle.net/PdwJ6/
HTML
Before
JS
$('#showMore').click(function() { $(this).toggle( function () { $(this).html('After');}, function () { $(this).html('Before'); }); });
不知道JsFiddle.net有什么用,但我不能发表演示。
您将两个函数嵌套在一起( .toggle()
.click()
和.toggle()
),而.toggle()
处理click
,这可能会导致冲突。 另外,使用text()
而不是html()
:
HTML :
Before
JavaScript :
$('#showMore').toggle(function() { $(this).text('Before'); }, function() { $(this).text('After'); });
Blender有适当的答案,但我们也可以将你的问题概括为一个简单的jQuery插件:
$.fn.toggleText = function(t1, t2){ if (this.text() == t1) this.text(t2); else this.text(t1); return this; };
您的代码将如下所示:
$('#showMore').click(function(){ $(this).toggleText('Before', 'After'); })
点击后切换的简单解决方案:
$('#showMore').on('click', function(){ $(this).html() == "after" ? $(this).html('before') : $(this).html('after'); });
如果您只是想切换,可以不用click()
。
$('#showMore').toggle( function() { $(this).html('After'); }, function() { $(this).html('Before'); });
有了这样的说法,你正在将放在另一个
内,这真的是你想要的吗? 或者你只是想替换
.text()
? .text("Before")
Jsfiddle toggle()
例子
这是相同答案的简化/“更紧凑”版本: “点击后切换的简单解决方案” 。
$('#showMore').on('click', function(){ $(this).html($(this).html() == 'after' ? 'before' : 'after'); });
当然这需要jQuery插件才能工作。
你应该只使用$(this).text('After')
和Before相同
我想你想使用在这种情况下效率不高的replaceWith()
因为只有文本改变了。
++其他答案中发现的切换错误。 感谢他们;-)
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; } });
用于:
$("#YourElementId").toggleText('After', 'Before');