jquery click event puzzle
This is a repeat post with more info...
I create a bunch of tags dynamically, appending them to a I then add a click handler...
$(document).ready(function(){
// ... code to append <a> tags to nav div
$("#nav a").click(function(event){
alert('Clicked '+event.target.id);
return false;
});
});
If I have 10 tags as a result of this and click the first one, I get 10 (TEN!) alerts - but they all show the id of the tag I actually clicked.
(If I click the 5th tag, yep, I get 5 alerts - all with the 5th tag's id...)
What's going on here? Is it because I dynamically created the tags? Is there a way to avoid it?
Here's the code that create the a tags
$(document).ready(function(){
$.get('_7day-M2.5.xml', {}, function(xml){
$(xml).find('entry').each(function(i){
$('#nav').append('<a href="#" id开发者_如何学编程="'+i+'">'+$(this).find("title").text()+"</a><br/>");
});
});
});
Firebug output reveals nothing odd looking.
Any idea what's going on here?
Thanks
Try using $("#nav > a") as your selector instead of $("#nav a"). If that doesn't work, then just make sure you are binding the click event outside of any loops that you might have. For instance if you have your click event binding inside of the $.each() that you have when creating the anchor tags, it's going to create more than one click event.
精彩评论