为什么这个不起作用?
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>');
});
});
为什么这个不起作用?
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>');
});
});
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');
});
$(this).html(($(this).html() == "after") ? 'before' : 'after')
- jave.webJsFiddle.net出了什么问题,但我无法发布演示。
你在嵌套两个函数(.click()
和.toggle()
),而.toggle()
处理一个click
,这可能会导致冲突。此外,使用text()
代替html()
:
HTML:
<a href="#" id="showMore">Before</a>
JavaScript:
$('#showMore').toggle(function() {
$(this).text('Before');
}, function() {
$(this).text('After');
});
$('#showMore').on('click', function(){
$(this).html($(this).html() == 'after' ? 'before' : 'after');
});
click
绑定到<a/>
上,然后在其中绑定toggle()
。click()
。$('#showMore').toggle(
function() {
$(this).html('<a href="#">After</a>');
},
function() {
$(this).html('<a href="#">Before</a>');
});
话虽如此,但您将<a/>
放置在另一个<a/>
内部,这真的是您想要的吗?还是您只想替换.text()
?.text("Before")
因为你把一个<a>
标签嵌套在另一个里面,导致像这样的结果:<a href="#" id="#showMore"><a href="">After</a></a>
你应该只是使用$(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');