Moving up multiple parents in jQuery - more efficient way?

前端 未结 6 546
庸人自扰
庸人自扰 2021-01-04 03:06

So, I have a navigation that is a list and has sublists and sublists.

Basically, the nav is by default collapsed, but if people click on a page that\'s in a sublist,

6条回答
  •  庸人自扰
    2021-01-04 03:11

    If I understand what you're trying to do... you can do something like this:

    // For my benefit, hide all lists except the root items
    $('ul, li', $('#lesson-sidebar ul li')).hide();
    
    // Show active parents and their siblings
    $('li a.active').parents('ul, li').each(function() {
        $(this).siblings().andSelf().show();
    });
    
    // Show the active item and its siblings
    $('li a.active').siblings().andSelf().show();
    

    The parents() and siblings() methods are both great for this kind of thing.

    Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.

    Edit 2: Now it works with class="active" on the anchor instead of the list item.

提交回复
热议问题