Suppose in code with the help of JQuery there is an event of clicking on the id = 'button' element:

$(function (){$('#button').click(function() { alert('на меня нажали'); }); }); 

The code works fine and everyone is happy, but if the #button element was removed and re-created using .innerHTML or for example its id was changed to another, and then replaced back to #button, the above written function stops working. As if jQuery thought that #button is no more. Question: what is this phenomenon and how can it be avoided? If not, how can you reanimate the function without refreshing the page?

added : the question intersects with this question, but I have a question about how to make the function work after the changes or find an alternative, and there is a question about the principle of the work of "delegation (delegation) and rebinding). Still can help in resolving this issue.

  • 2
    read about the delegation of events - lexxl
  • one
  • @Grundy is not a duplicate. There is the question "how it works," and then "how to do it." - Pavel Mayorov
  • @PavelMayorov, and unless knowing how it works will be a problem to understand how to do it? :-) - Grundy
  • @Grundy in response to that question there is not even a single code sample! Because the one who asked - was, as they say, "in the subject." Anyone who asks "how to do it" - will not understand from the explanations of "how it works" nothing at all. - Pavel Mayorov

2 answers 2

Use the following option

 $(document).on('click', '#button', function() { alert('на меня нажали'); }); 
  • Thanks, it helped. Applied - Vladislav Klimov
  • @ Vladislav Klimov, nezachto - Boris Runs
  • Waiting ready here was too much. - Pavel Mayorov
  • @ Vladislav Klimov notice the correction - Pavel Mayorov

The jQuery function you described will execute once, immediately after the page loads. If you then delete from the page, the element that was subscribed to the event, and then create it again. So for the newly created item, the subscription to the event you need does not yet exist. It needs to be executed again.

During the insertion of a button element into the document, after its next removal, simultaneously with these actions, subscribe to the event that you need. In other words, in the JS code, which describes how to insert a button, insert a function that will again subscribe this element to the event you need.

  • one
    Thanks for the answer. This solution with the re-call function after the element changes helped. I would stop at this if it were not for the mention of the function .on (). - Vladislav Klimov
  • I explained why it does not work =) The variant proposed with handling the click event on the button in the top-level element (body) is also correct. When it is used, it doesn’t matter what function you use to handle the .on () or .click () event, the result would be the same. - Evgeniy Miroshnichenko