I need this so that after the click I can exclude an element that I clicked from elements that have not been pressed yet
If this phrase means that in fact the handler needs to be executed only once for each element, then we can consider several ways to solve this problem.
The first:
when clicked, set an attribute indicating that the handler has already been invoked for this element.
$("#one, #two, #three").click(function(){ var done = $(this).data('done'); if(done) return; console.log($(this).attr('id') + ' clicked'); $(this).data('done', true); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="one">btn 1</button> <button id="two">btn 2</button> <button id="three">btn 3</button>
Second:
mark all elements as one class, attach the handler to the common parent by specifying the class as a selector. When clicking, remove the class from the item.
$("#wrapper").on('click', '.active', function(){ $(this).removeClass('active'); console.log( $(this).attr('id') + ' clicked' ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <button id="one" class="active">btn 1</button> <button id="two" class="active">btn 2</button> <button id="three" class="active">btn 3</button> </div>
Third:
disconnecting the handler from the item itself is the shortest option.
$("#one, #two, #three").click(function(e){ console.log( $(this).attr('id') + ' clicked'); $(this).off(e); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="one">btn 1</button> <button id="two">btn 2</button> <button id="three">btn 3</button>
If it’s still a question of leaving a handler, but knowing that an event has already been executed for a given element, then there are options - mark it with a data attribute, or add some class to the element.
$("...").click(function(){ $(this).addClass('clicked'); // или $(this).data('clicked', true); });
later, by obtaining the value of the attribute, or by checking the presence of the class .hasClass('active')
it is necessary that when you click on one of the elements that are processed by this event, it alone remains available, while others are blocked. And for that, I need to find out exactly which elements in the handler.
The simplest and most understandable option will be with the general handler on the parent element, and deleting the class from the other elements. Although the option with off should be similar.
$("#wrapper").on('click', '.active', function(){ console.log( $(this).attr('id') ) ; $('.active').not( $(this) ).removeClass('active'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <button id="one" class="active">btn 1</button> <button id="two" class="active">btn 2</button> <button id="three" class="active">btn 3</button> </div>
click(function(e){console.log(e.target)});- Mikhail Lelyakin