Re-register events with jQuery

I am adding new elements through jQuery to some of my projects, and I came across a slightly cumbersome problem.

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 next 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 start of the start event, subsequent events are not processed.

I understand that I can completely restructure and use the .bind() function, but due to the complexity of my project, this is actually not all that is possible.

How can I reset events after creating new elements without discarding anonymous functions, or is this possible?

+4
source share
4 answers

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

Update:

As mentioned on the page above:

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

+6
source

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 binding.

+1
source

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

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

For instance:

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

All Articles