0

我有一个菜单结构,其中子菜单位于页面其他地方的单独 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>

我似乎无法弄清楚如何做到这一点。任何帮助将不胜感激。谢谢!

4

2 回答 2

1

一种方法是从 id 中解析出数字。

   $('[id*="primary-nav-parent"]').on('mouseover mouseleave',function(){        
      $('[id$="sub-menu-' + this.id.match(/\d+/) + '"]').toggle();
   });

JSFIDDLE

于 2013-10-01T03:18:39.727 回答
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()
})

演示:小提琴

但更好的解决方案是

<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()
})

演示:小提琴

于 2013-10-01T03:08:56.390 回答