开发者

Updating "current" class in megamenu with jQuery

开发者 https://www.devze.com 2023-04-02 16:49 出处:网络
I have a menu which is stylized through jquery and CSS so the structure is like that: <div id=\"nav_top\" class=\"clearfix round_top\">

I have a menu which is stylized through jquery and CSS so the structure is like that:

<div id="nav_top" class="clearfix round_top">
    <ul class="clearfix round_all">
        <li class="current"><a href="index.php"><img src="images/icons/home.png"/>Home</a></li>

        <li><a href="#"><img src="images/icons/users_2.png"/>Users</a>
            <ul class="dropdown">
                <li><a href="users.php">Create user</a></li>
                <li><a href="view_users.php">View users</a></li>
                <li><a href="#" class="has_slide">Group management</a>
                    <ul class="slideout">   
                        <li><a href="#">View groups</a></li>
                        <li><a href="#">Manage permissions</a></li>
                    </ul>
                </li>
                <li><a href="#">Another menu item</a></li>
            </ul>
        </li>

    </ul>
</div>

So, as you can see, many levels could have an anchor.

The main idea is to have the TOP level with current because that's the only part you can see without hovering.

My first approach was to c开发者_如何学运维apture the current URL throuh window.location.pathname and then iterate through every $('#nav_top a') with a function like this one:

$('#nav_top a').each(function(){
if ( path.search($(this).attr('href') != -1){
   $(this).parent().parent().parent().addClass('current');
   $('.current').removeClass('current');
}
});

I also know I could select by href but I was going to make a performance test between both methods but, anyway, the point is that this works only for one of the levels because of the .parent() nesting.

How could I make this extensible to all levels?


You can try this out. Using the jQuery closest() http://api.jquery.com/closest/.

Notice that I also switched around removing and adding the class. The way you had it would just remove it from the element you just added it to.

$('#nav_top a').each(function(){
   if ( path.search($(this).attr('href') != -1){
      $('.current').removeClass('current');
      $(this).closest('.top-level').addClass('current');
   }
});

Edit:

Add a class of top-level to your top level <li>s

0

精彩评论

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