There is such a code

$("#start").click(function(){ $(this).attr("id", "submit"); }); $("#submit").click(function(){ alert("something"); }); 

Question: why is the alert not executed when clicking on the same item? After all, I changed his id to another when I first clicked, therefore, I expect that actions will be performed when clicking on the same element already with the id of "submit", but this does not happen.

  • because at the moment of adding an element handler with such an id was not yet, therefore it was not added anywhere. In addition, changing the id does not remove already added handlers - Grundy

3 answers 3

The fact is that when you handle a push function for an alert, the #submit element #submit not exist. You need to add a global handler for clicking on this item:

 $("#start").click(function() { $(this).attr("id", "submit"); }); $(document).on("click", "#submit", function() { alert("something"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="start">НаТми</button> 

  • If it were not for your "click" button, then I was ready to believe that you yourself wrote this code :) - MasterAlex
  • That is, I correctly understand that the code first undergoes preprocessing, in which here such non-existent handlers are discarded, and even if you later assign a click on the element to which the handler was bolted, will it not appear dynamically? - Muller
  • @Muller, right - Yuri
  • @MasterAlex, I was too lazy to write again. But I would add instead of body - document , it would be more correct, as for me - Yuri
  • one
    @Grundy, if the article is outdated, then the refutation in the studio :) -

This is how it works:

 $("#start").click(function() { $(this).attr("id", "submit"); }); $("body").on("click", "#submit", function() { alert("something"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="start">НаТми</button> 

  • Sorry to steal the answer :) - Yuri

 $("#start").click(function(){ $(this).attr("id", "submit"); $(this).click(function(){ alert("something"); }); }); 
 <script src="https://code.jquery.com/jquery-2.0.3.js"></script> <div id="start">start</div> 

  • one
    and for each click to add another handler? - Grundy