I linked delegated event handlers to several elements on the page using a single selector. Since events are triggered for individual elements, I would like to disable only the event handler of this element based on some conditional logic . This means that I do not necessarily want to disable the event on the first click . But I can’t figure out how to do this without disconnecting them all.
HTML:
<button>One</button> <button>Two</button> <button>Three</button>
JS:
$(document).on('click', 'button', function(ev) { // doesn't work because argument needs to be a string $(document).off('click', $(ev.target)); // doesn't do what I want b/c turns off events on all buttons, not just this one $(document).off('click', 'button'); // doesn't work because event is on document, not button $(ev.target).off('click'); });
jQuery , , jQuery ($(ev.target)), , , .
$(ev.target)
jQuery:
, . , .on(), . , "**".
, ?
JSFiddle
UPDATE: , , .
- ! . .
$(document).on('click', '.btn', function (ev) { alert('pressed'); $(this).removeClass("btn"); });
@Fiddle
<button class="btn">One</button> <button class="btn">Two</button> <button class="btn">Three</button>
: ? LIke LShetty , . , . ,
$('button').on('click', function(ev) { $('#output').append('Clicked! '); $(this).off('click'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <button>One</button> <button>Two</button> <button>Three</button> <div id="output"></div>
, lshettyl ( ) - , , , stopPropagation() .
, , DOM , . , , , , , - .
$(document).on('click', 'button', function(ev) { // Your logic to occur on button click // Prevent further click on just this button $(this).click(function(event) { event.stopPropagation(); }): });
, .
- :
$('button').on('click', function(ev) { $(this).off('click'); });
$(document).on('click', 'button', function(ev) { $(ev.target).off('click'); });