开发者

Replacing Text in a Toggled Anchor with JQuery

I'm trying to change the text in an anchor on toggle. I'm doing this way at the moment but have found that once the anchor markup has replaced the toggle no longer works. Can someone please explain why this is happening and a solution? Man开发者_如何转开发y thanks.

    $('a#toggleHeader').toggle(function() {
    $('#header-wrapper').slideUp();
    $(this).replaceWith('< href=\"#\" id="toggleHeader">Show Header</>');

//Note:I've move the anchor because I can only post one anchor as a new user

},function(){
    $('#header-wrapper').slideDown();
    $(this).replaceWith('<a href=\"#\" id="toggleHeader">Hide Header</a>');

});


Simply change the contents of the anchor, instead of replacing the whole thing:

$('a#toggleHeader').toggle(function() {
    $('#header-wrapper').slideUp();
    $(this).text('Show Header');
}, function () {
    $('#header-wrapper').slideDown();
    $(this).text('Hide Header');
});

The reason why it was no longer working, is because the event handlers were being lost when the anchor was being removed (and replaced). If you wanted your example to work, you would either need to rebind the events each time they were replaced, or bind the events using the live() or delegate() methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜