jQuery .toggle()显示和隐藏子菜单 [英] jQuery .toggle() to show and hide a sub sub-menu
问题描述
我正在使用此问题的代码进行显示/隐藏切换
I'm using this question's code to make a show/hide toggle
$('#menu-lateral .sub-menu').hide(); //Hide children by default
$('#menu-lateral > li > a').click(function() {
event.preventDefault();
$(this).siblings('.sub-menu').slideToggle('slow');
});
问题是我的子菜单有自己的子菜单,其中包含许多项目.有没有办法使此代码适应下一级的要求?
The problem is that my sub-menu has its own sub-menu with many items. Is there a way to adapt this code to work ALSO in the next level?
重要信息:默认情况下,wordpress使子UL具有相同的类,因此它们都是.sub菜单.
赞:
<ul id="menu-lateral" class="menu">
<li id="menu-item-29"><a href="#">Parent Level 1</a>
<ul class="sub-menu">
<li id="menu-item-108"><a href="#">Parent Level 2</a>
<ul class="sub-menu">
<li id="menu-item-104"><a href="#">Element</a></li>
</ul>
</li>
</ul>
</li>
</ul>
提琴: http://jsfiddle.net/qfygM/1/
感谢您的帮助!
更新:可以在这里找到解决方案>> http://jsfiddle.net/qfygM /7/
UPDATE: The solution may be found here >> http://jsfiddle.net/qfygM/7/
Zenith制造.
$('#menu-lateral .sub-menu').hide(); //Hide children by default
$('#menu-lateral li a').click(function(event){
if ($(this).next('ul.sub-menu').children().length !== 0) {
event.preventDefault();
}
$(this).siblings('.sub-menu').slideToggle('slow');});
推荐答案
是的,在这种情况下,您可以仅使用后代选择器-$('#menu-lateral li a')
作为选择器,而不是当前使用的直接子选择器-$('#menu-lateral > li > a')
.
Yes, in this case you could just use the descendant selector - $('#menu-lateral li a')
as your selector as opposed to the direct child selector you're currently using - $('#menu-lateral > li > a')
.
当您现在使用后代选择器时,所有将来的降序级别"都将在您的$(this).siblings('.sub-menu').slideToggle('slow');
语句中分别作为目标,使其易于扩展.
As you're now using the descendant selector, all future descending 'levels' will be targeted individually in your $(this).siblings('.sub-menu').slideToggle('slow');
statement, making it very easily extendable.
这篇关于jQuery .toggle()显示和隐藏子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!