Categories
jquery list

Why does my jQuery alert show twice?

I am using jQuery. I have a problem when alerts the IDs of a list shows two times, instead of once.

The list:

<ul id="testnav">
<li> <a href="#">Page 1</a></li>
<li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>
</ul>

The code:

$("li").click(function(){
var current_id = $(this).attr('id');
alert(current_id);
// These alert two times, one is empty and another one is content_1
});

Why dopes the code alert two times? How do I make it execute a single time?

$(“li”).click() is applying the click event to all LIs on the page.

When you click

<li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>

You’re actually clicking the outer LI, and the inner-most LI, which would cause the event to fire twice. The outer LI has no ID, so it’s empty, and the inner LI has an ID of “content_1”, so that displays.

Does that make sense?