简体   繁体   中英

Get child <ul> in <ul> list without id and with e.preventDefault() on first level of <ul><li><a>

I have some menu with structure like this:

<ul id="menu">
    <li><a href="#"><span>First level link 1</span></a>
        <ul>
            <li><a href="#"><span>Child link 1</span></a></li>
            <li><a href="#"><span>Child link 2</span></a></li>
        </ul>
    </li>
    <li><a href="#"><span>First level link 2</span></a>
        <ul>
            <li><a href="#"><span>Child link 2</span></a></li>
            <li><a href="#"><span>Child link 2</span></a></li>
        </ul>
    </li>
</ul>

It need to show only first level ul li, its ok, but then it needs to show by on click second level links. And i cant usw id or rel attr in ul or li - this is my problem to catch child .

My code is like:

var menuRaw = $("ul#menu > li:lt(5)");

    menuRaw.click(function(e){
        e.preventDefault();

        var menuItem = $(this);

        menuRaw.removeClass("selected");
        menuItem.addClass("selected");

        $('#menu ul').hide();
        menuItem.find("ul").show();
    }

And it works but e.preventDefault() is blocking all links in menu (but on second level links needs to be working links as normally they do)

Sorry for my English, and this is first question on stackoverflow.

You can select and process the clicks for each level like:

// first level links
$("ul#menu > li > a").click(function() {
    e.preventDefault();

    // show sub-menu etc..
}

// second level links (remove this block if you dont want any spl processing here)
$("ul#menu > li > ul > li > a").click(function() {
    return true; // behave like normal links
});

You can achieve this by checking if the clicked li has any ul 's nested within it.

$('#menu li').click(function(e) {

  $this = $(this);
  e.stopPropagation(); 

  if ($this.has('ul').length) {
    e.preventDefault();
    $('ul', this).fadeToggle();
  } 

});

Here's a demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM