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 fired, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With