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:
- <head>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
- <script type='text/javascript'>
- $(document).ready(function() {
-
- $("p").append("<a href='' class='newlink'>Hey you</a>");
-
- $(".newlink").click(function(event) {
- alert("You clicked me! :O");
- event.preventDefault();
- });
-
- $('#makelink').click(function(event) {
- $("p").append("<a href='' class='newlink'>Hey you</a>");
- event.preventDefault();
- });
- });
- </script>
- </head>
- <body>
- <a href='' id='makelink'>Make another link</a>
- <p></p>
- </body>
Could someone explain to me what's going on, and perhaps how I can resolve this? Thanks in advance!