我有一个菜单结构,其中子菜单位于页面上其他位置的单独div中。父元素和子菜单都已编号,我正在尝试找到一种方法来翻转父元素并打开其相应的子菜单,而不必为每个子元素使用单独的选择器。父元素如下所示:
<li id="primary-nav-parent-0"></li>
<li id="primary-nav-parent-1"></li>
<li id="primary-nav-parent-2"></li>
<li id="primary-nav-parent-3"></li>
<li id="primary-nav-parent-4"></li>
<li id="primary-nav-parent-5"></li>
子菜单看起来像这样:
<div id="primary-nav-sub-menu-0" class="primary-nav-sub-menu"></div>
<div id="primary-nav-sub-menu-1" class="primary-nav-sub-menu"></div>
<div id="primary-nav-sub-menu-2" class="primary-nav-sub-menu"></div>
<div id="primary-nav-sub-menu-3" class="primary-nav-sub-menu"></div>
<div id="primary-nav-sub-menu-4" class="primary-nav-sub-menu"></div>
<div id="primary-nav-sub-menu-5" class="primary-nav-sub-menu"></div>
我似乎无法弄清楚如何实现这一目标。任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
一种方法是
var $subs = $('.primary-nav-sub-menu').hide();
$('li[id^=primary-nav-parent-]').click(function(){
var $target = $('#primary-nav-sub-menu-' + $(this).index());
//or var $target = $('#primary-nav-sub-menu-' + this.id.match(/(\d+)$/)[1]); if you don't want to depend on the index
$subs.not($target).stop(true, true).slideUp();
$target.stop(true, true).slideDown()
})
演示:Fiddle
但更好的解决方案是
<ul>
<li id="primary-nav-parent-0" class="primary-nav-parent" data-target="#primary-nav-sub-menu-0">0</li>
<li id="primary-nav-parent-1" class="primary-nav-parent" data-target="#primary-nav-sub-menu-1">1</li>
<li id="primary-nav-parent-2" class="primary-nav-parent" data-target="#primary-nav-sub-menu-2">2</li>
<li id="primary-nav-parent-3" class="primary-nav-parent" data-target="#primary-nav-sub-menu-3">3</li>
<li id="primary-nav-parent-4" class="primary-nav-parent" data-target="#primary-nav-sub-menu-4">4</li>
<li id="primary-nav-parent-5" class="primary-nav-parent" data-target="#primary-nav-sub-menu-5">5</li>
</ul>
然后
var $subs = $('.primary-nav-sub-menu').hide();
$('.primary-nav-parent').click(function(){
var $target = $($(this).data('target'));
$subs.not($target).stop(true, true).slideUp();
$target.stop(true, true).slideDown()
})
演示:Fiddle
答案 1 :(得分:1)
一种方法是解析id中的数字。
$('[id*="primary-nav-parent"]').on('mouseover mouseleave',function(){
$('[id$="sub-menu-' + this.id.match(/\d+/) + '"]').toggle();
});