tags:

views:

2895

answers:

5

I am using JQuery. I have problem when Alerts the IDs of 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 another one is content_1


   });

Any one explain why the code alerts two times? How do I make it execute a single time?

+3  A: 

You are experiencing event bubbling.

Luca Matteis
+5  A: 

You have a <li> nested inside another <li>.

When you click on the inner <li>, you will get the event for the inner <li> and the outer <li>

Change you html to...

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

and you will get alerts of "Content_1" and "OUTER-LIST-ITEM" which make it clearer what is going on...

rikh
+3  A: 

$("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?

Carl
A: 

Because $("li") returns a all matching objects. So when you click one, the one with id=content_1, you also click its parent which does not have an id.

Mike_G
A: 

It alerts once for each li and your link is two lists deep. To fix it, assuming you only want subnav items to trigger, change the first line of your code to

$("#subnav li").click(function(){

If you need more lists create a class to identify lists you want to attach to the click event.

Philip T.