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>
开发者_Python百科
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.
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 li
s -- 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.
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]);
精彩评论