Situation:
there is an element

<span class="edit">текст</span> 

and there is a handler

 $('.edit').click(function() { $(this).addClass('absolute').removeClass('edit'); $(this).html('<input type="text" value="'+$(this).text()+'"><input class="ok" type="button" value="ok">'); }); 

when you first click on an element, which is logical, an input with the same content and an "ok" button appear inside it. however, when you click on an element again (on an input or a button), the same event appears, and an input is created anew with a button, instead of these, with an empty value, although the class "edit" from which the event fires, was removed.

Where is the error in my reasoning? why it happens?

  • Thank you all for the clarification :) the question is closed - Garfild

4 answers 4

And you can do it at the very beginning of the handler:

 if (!$(this).hasClass('edit')) return; 

And this happens because events are tied to an element, and not to a selector - therefore, with the selector changed, events continue to work.

Accordingly, in the event, which should return the activity - again add the class edit .

  • Thanks, I liked this option the most! - Garfild

To achieve the desired effect, you can use .on ()

as

 $('.edit').parent().on('click', '.edit', function () { var $this=$(this); $this.addClass('absolute').removeClass('edit'); $this.html('<input type="text" value="' + $this.text() + '"><input class="ok" type="button" value="ok">'); }); 

example to exclude future issues

    You can for example untie the click event after the first click http://jsfiddle.net/3AkaD/

    • it is necessary that after another event (click outside and then remove the input) the original event also works. to bind again? - Garfild
    • Yes, or in the case of a class, add the class again. - Gena Tsarinny

    The class only serves as a reference to the element and after its removal the binding remains. To disable event triggering, you can use either $(this).off('click'); either inside the handler, check for the presence of a class (if not, then e.preventDefault() or return false; ), or use .one() in general.