jQuery Event How to - Add element and hook up event handler








Question

We would like to know how to add element and hook up event handler.

Answer


<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head><!-- www.  j  a v  a2  s .  co m-->
<body>
  <ul>
  </ul>
  <script>
    var projects = [{title:'Project 1'},{title:'Project 2'}];
    $.each(projects, function(i){
      $("<a/>", { href:'#', text:projects[i].title })
        .click(function(e){console.log( projects[i].title );})
        .wrap("<li></li>")
        .parent()
        .appendTo("ul");
    });
    </script>
</body>
</html>

The code above is rendered as follows: