tags:

views:

172

answers:

3

Dear all I am using JQuery My list has following

<div id="wrapper">

        <ul id="testnav">

            <li class="test1"><a href="/link">Heading</a>
                 <ul>
                    <li><a href="/link">Sub Heading</a></li>
                    <li><a href="/link">Sub Heading</a></li>
                   <li><a href="/link">Sub Heading</a></li>
                 </ul>
            </li>
            <li class="test2"><a href="/link">Heading</a>
                <ul>
                    <li><a href="/link">Sub Heading</a></li>
                    <li><a href="/link">Sub Heading</a></li>
                    <li><a href="/link">Sub Heading</a></li>
                </ul>
            </li>
            <li class="test3"><a href="/link">Heading</a>
                <ul>
                    <li><a href="/link">Sub Heading</a></li>
                    <li><a href="/link">Sub Heading</a></li>
                    <li><a href="/link">Sub Heading</a></li>
                </ul>
            </li>
        </ul>

    </div>

When i click the heading or sub Heading I need that corresponding text I used the following it not working

$("li").bind("click", function(){
     alert( $(this).text());
});

What change should I make?

+2  A: 
 $("li a").bind("click", function(){
     alert( $(this).text());
 });

The li's text is actually an A link text. So you need to get that. that would only work for the children.

I'm not sure LIs have a click event but it would have worked if you'd use the html() function instead of text():

 $("li").bind("click", function(){
     alert( $(this).html() );
 });
bchhun
+1  A: 

You were very close - you need to bind the event to the anchor tag and make sure that you wrap your event binding in a $(document).ready function like so:

$(document).ready(function() {
    $("li a").bind("click", function() { alert( $(this).text()); })
});
Andrew Hare
+1  A: 

Though neither of the other answers are incorrect, I'd do it like this:

$('#testnav a').click(function(ev){
    alert($(this).text())

    //if you need to stop the browser going to the link
    // (eg you're doing something else AJAXey):
    ev.preventDefault();
    ev.stopPropagation();
});

If the reason you were trying to attach to the lis directly is you want the whole thing to be "clickable", use CSS to resize your links:

#testnav a { display:block }

Depending on how you're doing it, you might need to play around making the link, li and/or ul float, and set widths.

Oli
use event delegation instead of adding lots of individual handlers
redsquare