开发者

Re-register events with jQuery

I have been adding new elements via jQuery in some of my projects, and I have stumbled across a bit of a cumbersome issue.

Consider the following:

$('span.claim').click(function() {
    $(this).parent().html('<span class="unclaim">Unclaim</span>'):
});

$('span.unclaim').click(function() {
    $(this).parent().html('<span class="claim">Claim</span>'):
});

And the following markup...

<ul>
    <li><span class="claim">Claim</span></li>
    <li><span class="unclaim">Unclaim</span></li>
    <li><span class="claim">Claim</span></li>
    <li><span class="unclaim">Unclaim</span></li>
</ul>

Unfortunately, after the initial event is fi开发者_运维知识库red, no subsequent events are handled.

I realize I could completely restructure and use the .bind() function, but because of the complexity of my project this isn't really all that feasible.

How would I go about re-binding the events after the new elements are created without ditching my anonymous functions, or is it even possible?


You probably want to look at jQuery live events: http://docs.jquery.com/Events/live

Update:

As mentioned on the above page:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().


Option 1:

$('a.claim').click(function() {
    $(this).html('Unclaim').addClass('unclaim').removeClass('claim');
});

$('a.unclaim').click(function() {
    $(this).html('Claim').addClass('claim').removeClass('unclaim');
});

Option 2:

function bindClaim(){
$('a.claim').unbind('click').click(function() {
    $(this).parent().html('<span class="unclaim">Unclaim</span>');
    bindUnclaim();
});
}

function bindUnclaim(){
$('a.unclaim').unbind('click').click(function() {
    $(this).parent().html('<span class="claim">Claim</span>');
    bindClaim();
});
}

bindClaim();
bindUnclaim();

Option 3 (recommended):

http://docs.jquery.com/Events/live instead of bind.


No need for .live() or re-binding this one. You only need one method:

$('.claim,.unclaim').click(function() {
    var claimed = $(this).hasClass('claim') ? 'Unclaim' : 'Claim';
    $(this).text(claimed).attr('class', claimed.toLowerCase());
});


For example:

clickBtn.on("click.claim", evt => {
    clickBtn.off("click.claim");
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜