append not added to DOM when called inside click function

append not added to DOM when called inside click function

I am sort of muddling my way through teaching myself jQuery, and I've finally run into a wall that I can't get around.

I call append() on an element in the DOM, adding a new element inside it. I make a click handler for the new element, and everything works fine.

But when I call append() inside a click handler, the resulting element is not recognized by my selector, and I'm guessing it's not actually added to the DOM. Here's my simplified code; hopefully you can make sense of it:

  1. <head>
  2.     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  3.     <script type='text/javascript'>   
  4.         $(document).ready(function() {
  5.            
  6.             $("p").append("<a href='' class='newlink'>Hey you</a>");
  7.            
  8.             $(".newlink").click(function(event) {
  9.                 alert("You clicked me! :O");
  10.                 event.preventDefault();
  11.             });
  12.            
  13.             $('#makelink').click(function(event) {
  14.                 $("p").append("<a href='' class='newlink'>Hey you</a>");
  15.                 event.preventDefault();
  16.             });
  17.         });
  18.     </script>
  19. </head>
  20. <body>
  21. <a href='' id='makelink'>Make another link</a>
  22. <p></p>
  23. </body>

    Could someone explain to me what's going on, and perhaps how I can resolve this? Thanks in advance!