用jQuery提升多个父母 – 更有效的方式?

所以,我有一个列表导航,并有子列表和子列表。

基本上,导航默认是折叠的,但是如果人们点击子列表中的页面,我想显示父列表。 如果它是子列表的子列表,我需要显示两个父列表。 我已经设置了,但是,我不喜欢将5 .parent()。parent()向上移动以扩展列表。 有更有效的方法吗?

HTML:

jQuery:

 function toggleSubmenu() { if ($(this).hasClass('submenu-hidden')) { $(this).parent().children('ul').slideToggle(); $(this).removeClass().addClass('submenu-visible'); } else if ($(this).hasClass('submenu-visible')) { $(this).parent().children('ul').slideToggle(); $(this).removeClass().addClass('submenu-hidden'); } } $('#lesson-sidebar ul ul').hide(); $('#lesson-sidebar ul ul ul').hide(); $('#lesson-sidebar ul:first-child').attr('id', 'rootlist'); $('#lesson-sidebar ul li:has("ul")').prepend('').css('list-style','none'); $('#lesson-sidebar ul li a').each( function() { if ($(this).hasClass('active')) { // if it is a UL var length = $(this).parent().find("ul").length; alert(length); if (length == 0) { if ($(this).parent().parent().parent().children('span').hasClass('submenu-hidden')) { $(this).parent().parent().parent().children('ul').show(); $(this).parent().parent().parent().children('span').removeClass('submenu-hidden').addClass('submenu-visible'); } if ($(this).parent().parent().parent().parent().parent().children('span').hasClass('submenu-hidden')) { $(this).parent().parent().parent().parent().parent().children('ul').show(); $(this).parent().parent().parent().parent().parent().children('span').removeClass('submenu-hidden').addClass('submenu-visible'); } } if (length == 1) { $(this).parent().find('ul').slideToggle(); $(this).parent().children('span').removeClass('submenu-hidden').addClass('submenu-visible'); } } } ); $('ul#rootlist > li span, ul#rootlist li ul li > span').bind('click', toggleSubmenu); 

任何和所有帮助都非常感谢。

如果我明白你要做什么……你可以这样做:

 // 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(); 

parent()和siblings()方法都非常适合这种事情。

编辑:之前有一个错误,它没有显示父兄弟姐妹。 试试这个新版本。

编辑2:现在它在锚点上使用class =“active”而不是列表项。

$(this).closest("ul")将遍历父项,直到找到ul

http://docs.jquery.com/Traversing/closest#expr

…通过测试元素本身并遍历DOM树中的祖先来获取与选择器匹配的第一个元素…

为了简化Lance McNeary非常有用的答案,诀窍是使用:

 .parents([selector]) 

给定一个表示一组DOM元素的jQuery对象,.parents()方法允许我们在DOM树中搜索这些元素的祖先,并从直接父对象中排序的匹配元素构造一个新的jQuery对象; 元素按从最近的父元素到外元元素的顺序返回。

另一位用户建议:

 .closest([selector]) 

与.parents()类似,这可能是一个更好的选择,因为它一旦找到它正在寻找的元素就会停止。 在这种情况下似乎更有效率。 有关详细信息,请参阅http://api.jquery.com/closest/ 。 希望这有助于人们理解.closest()和.parents()之间的差异以及jQuery的强大和灵活性。

$(this).parents().get()[4]会给你第五个

尝试使用此代码行:

 $(this).parent().parent().fadeOut();