2

Any one can tell me why the with the code below I get the alert "Hello world" working on link #1 and link #2 only?

The link #3 is generated after doing a ajax call and the click event seems to be simply not available. I can't figure it out why.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Test Page</title>
    <script src="media/js/jquery-1.10.2.js"></script>
    <script src="media/js/jquery-ui.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {

          $("#message").append('<a href="#" class="view_comments" id="2">Link #2</a><br />\n');

          $(".view_comments").click(function() 
            {
            alert('Yes it worked!');
          });

          UpdateDiv();

          function UpdateDiv() {
            var var_1 = "1";
            var var_2 = "2";
            $.getJSON('file.php', {var1: var_1, var2 : var_2},function(json_result){
              $("#message").append('<a href="#" class="view_comments" id="3">Link #3</a><br />\n');
              $("#message").show();
            });
          }

        });
    </script>
    </head>
    <body>
        <div id="message" name="message"><a href="#" class="view_comments" id="1">Link #1</a><br /></div>
    </body>
</html>
JJJ
  • 32,902
  • 20
  • 89
  • 102
Terry
  • 21
  • 1

2 Answers2

3

Delegate your click event:

$('body').on( 'click', ".view_comments", function()
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

The click event is registered for already loaded items. Any element added dynamically don't seems having that event registered and hence the click event won't work. At least, I run into this issue before. But the following will fix it.

 $(".view_comments").on("click",function(){
 {
       //alert('Yes it worked!');
 });

Look the "on" JQuery API documentation

user3818435
  • 707
  • 2
  • 9
  • 16