views:

61

answers:

3

I'm writing some jquery to programmatically build a list of links and I'd like to attach a click() event to each link. I'm having trouble getting the click function to fire. Can anyone point me in the right direction on how to do this?

This is what I have so far:

<!doctype html>
<html>
<head>
<title></title>

<script type="text/javascript" src="helper/jquery-1.4.2.min.js"></script>  
<script type="text/javascript">                                         
$(document).ready(function() {
    var markup = '<li><a href="#myLink1">some link</a></li>';
    var $newLink = $(markup);
    $newLink.appendTo('.myLinks ul');
    $newLink.show();

    $("ul.myLinks li").click(function() {
        alert('hello');
    });
});
</script> 

</head>

<body>
  <div class="myLinks">
    <ul>
    </ul>
  </div>

</body>
</html>
+2  A: 

Your mistake is here:

$("ul.myLinks li").click(function() {
    alert('hello');
});

That should be .myLinks ul li instead, as your myLinks class is on a <div>, not a <ul>.

If that still doesn't work, then Evgeny is right in that you should be attaching click events to your <a>s and not their containing <li>s.

BoltClock
Better yet, OP should use `.delegate()` and then only one function will be attached and any/all of the `li`'s in the `ul` will have that event handler.
Jeff Rupert
@Jeff Rupert +1, Thanks, this is something new i learnt.
naikus
Thanks, this solved my problem.
mksuth
+1  A: 

In addition to what BoltClock said, it looks like you're attaching the event handler to the list items, rather than the hyperlinks inside them. Try $(".myLinks ul li a").

I would also test the selector to make sure it's returning what you want. Step through it in Firebug or do something like alert($(".myLinks ul li a")[0]);

Evgeny
+1  A: 

You could try something like this:

$('div.myLinks ul')
  .append( '<li><a href="#myLink1">some link</a></li>' )
  .delegate( 'a','click', function(e){
    e.preventDefault();
    alert('hi');
  });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Here's a working example.

Of course, the .append() would more likely be a bunch of lis -- something you can build any number of ways:

var $bunchOfLi = $('<li><a href="#myLink1">some link</a></li>')
  .add('<li><a href="#myLink2">another link</a></li>')
  .add('<li><a href="#myLink3">yet another link</a></li>');

...and thus:

.append( $bunchOfLi )

...as in this working example.

Ken Redler
This is more or less exactly what I need going forward. Thanks for the working examples!
mksuth
@mksuth, glad to help. Whether this or another, don't forget to accept an answer. Doing so makes it more likely you'll get answers to your questions in the future.
Ken Redler