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:46

Not sure what's up with JsFiddle.net, but I can't post a demo.

You're nesting two functions within each other (.click() and .toggle()), and .toggle() handles a click, so that might be causing 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');
});
查看更多
登录 后发表回答