Search code examples
javascriptjqueryjquery-load

After loading html for a div with jQuery, existing codes/functions doesn't work for loaded content


Maybe you understood from the title however here I go:

I have a file, from that file I load some other data from a php file:

File 1 html file

<html>
     <head>
      <script type="text/javascript" src="js/jquery.js"></script>
      <script type="text/javascript">
          $(function() {
               $('#content').load('source.php');

               $("#link").click(function() {
                       alert('Message1!');
                       return false;
               });
          });
      </script>
     </head>

     <body>
           <div id="content"></div>
     </body>
</html>

File source.php

<?php

for($i=1;$i<=10;$i++) {

     echo '<a href="#" id="link">Link '.$i.'</a>';

}

?>

After the content is loaded from the php file now this code

$("#link").click(function() {
        alert('Message1!');
        return false;
});

doesn't work for loaded content(links).

I need just an explanation how this DOM works, why loaded content can't interact with active functions/codes?


Solution

  • you just have to use live instead of click for example

    $("#link").live('click', function() {
            alert('Message1!');
            return false;
    });
    

    EDIT :

    I learned just now that it is deprecated since JQuery 1.7 so now we have to use .on() function like :

    $("#link ").on("click", function(event){
        alert('Message1!');
        return false;
    });
    

    http://api.jquery.com/live/

    http://api.jquery.com/on/