With the following html and jQuery, if I click the first anchor multiple times and then click the list anchor I get the alert message show up by the number of times I clicked the first anchor. Why is this? How do I stop it happening?
<div>
<a href="#">click me</a>
<ul style="display:none">
<li><a href='#'>now click me</a></li>
</ul>
</div>
$('div > a').click(function(e) {
e.preventDefault();
$(this).next().show().find('a').click(function() {
alert("alert from inner click");
return false;
});
});
Because every time your click handler for the anchor is called, you’re hooking up another instance of an event handler for the other anchor. Presumably you only want to hook it up once, but without knowing more about what you’re trying to actually do…
If you’re trying to change what happens on the second anchor when you click the first, you can unbind all
clickhandlers from the anchor first, like this:…but I suspect with a better idea of the overall goal, there would be a better solution. (One problem of the above is that it removes all
clickhandlers from the anchor, whether hooked up by that code or something else, which isn’t playing nicely with others.)