jQuery: Preventing an event from being attached more than once?
Essentially, I have an element FOO
that I want when clicked to attach a click event to a completely separate set of elements BAR
, so that when they're clicked they can revert FOO
to its previous content. I only want this event attached once.
When FOO
is clicked, its content is cached away in $back_up
, and a trigger is added on the BAR
set so that when clicked they can revert FOO
back to its previous state. Is there a clever way to do this? Like to only .bind()
if the event doesn't already exist?
$('<div class="noprint little check" />').click( function () {
var $warranty_explaination = $(this).closest('.page').children('.warranty_explaination');
var $back_up = $warranty_explaination.clone(true);
$(this).closest('.page').find('.warranties .check:not(.noprint)').click( function () {
/* This is the code I don't want to fire more than once */
/*, I just want it to be set to whatever is in the $back_up */
alert('reset'); $warranty_explaination.replaceWith( $back_up )
} );
$warranty_explaination.html('asdf')
} )
Currently, the best way I can think to do this is to at开发者_运维百科tach a class, and select where that class doesn't exist.
Unless I misunderstood, I think you are looking for the one
function to bind events. It is just like bind
, except it removes the handler after the first invoke.
Alternatively, you could store a flag in .data
and look for it within your click handler.
You can unbind handlers for a given event from an element using unbind.
$(this).closest('.page').find('.warranties .check:not(.noprint)').unbind("click");
$(this).closest('.page').find('.warranties .check:not(.noprint)').click(function() ...
http://docs.jquery.com/Events/unbind
精彩评论