开发者

How to set the parent class of an unordered list

开发者 https://www.devze.com 2023-01-11 07:41 出处:网络
I have the following ul setup: <div id=\"sidebar\"> <ul id=\"themenu\" class=\"sf-menu sf-vertical\">

I have the following ul setup:

        <div id="sidebar">
        <ul id="themenu" class="sf-menu sf-vertical">

            <li>
                <a class="sf-with-ul topm" href="#">Musical Instruments</a>
                <ul class="bullet">
                    <li><a href="#">Guitars</a></li>
                    <li><a href="#">Drums</a></li>
                    <li><a href="#">Keyboards</a></li>
                    <li><a href="#">Brass</a></li>
                </ul>
            </li>
        </ul>
        </div>

My question is, in addition to the above, I have other top-level menus with sub-menus that when a top-level menu is selected, it is highlighted "Green" based on a class I have created called "currentMenu".

My jQuery works fine for top-level menu items for setting them to "Green" as each top-level menu is toggled but what I am unsure how to do, is that when the user se开发者_Python百科lects say the sub-menu "Drums" in the above code, I want it's parent top-level menu set to "currentMenu" class. In this case, the top-level button "Musical Instruments" would be set.

I am unsure how to do. I tried something like:

    $('ul.sf-menu li a').click(function() {

        if($(this).hasClass('nosub')) {
            $("ul.sf-menu li ul li a").removeClass("currentSubMenu");
        }
        else {
            $("ul.sf-menu li a").not(this).removeClass("currentMenu");
            $("ul.bullet li a").parent().this.addClass("currentMenu");
        }
    });     

It's this line I'm not sure about:

$("ul.bullet li a").parent().this.addClass("currentMenu");


I think this is what you're after. Instead of this:

$("ul.bullet li a").parent().this.addClass("currentMenu");

You can use .closest() to get there, like this:

$(this).closest('.sf-menu > li').children('a').addClass('currentMenu');

This goes from the link you clicked on up to the first level <li> it's in, and applies the .currentMenu class to it's <a> child.


Or, if you want .currentClass applied at each level you're in, you can do this:

$(this).parents('li').children('a').addClass('currentMenu')
       .end().siblings().children('a').removeClass("currentMenu");

You can give it a try here.

0

精彩评论

暂无评论...
验证码 换一张
取 消