遍历无序列表(nav)

时间:2012-01-23 04:36:36

标签: jquery iteration event-listener megamenu

我正在使用Mega菜单并使用无序列表触发事件以显示Mega菜单。 这是Nav Bar的HTML代码:

<div class="alpha omega grid_15" id="topNavLink">
    <ul id="navRollOver">
      <li><a href="#" title="SOCCER" target="_self" >SOCCER</a></li>
      <li><a href="#" title="TENNIS" target="_self" >TENNIS</a></li>
      <li><a href="#" title="BASEBALL" target="_self" >BASEBALL</a></li>
      <li><a href="#" title="BASKETBALL" target="_self" >BASKETBALL</a></li>
      <li><a href="#" title="FOOTBALL" target="_self" >FOOTBALL</a></li>
      <li><a href="#" title="GOLF" target="_self" >GOLF</a></li>
      <li><a href="#" title="RUGBY" target="_self" >RUGBY</a></li>
      <li><a href="#" title="HOCKEY" target="_self" >HOCKEY</a></li>   
    </ul>
  </div>

我正在使用课程subNavContainer调用div,css状态为display: none;

这就是我想要做的......我打算获取所有li和目标> a的数组并听取鼠标输入事件以触发mega菜单{{{ 1}}。

我需要帮助,通过slideDown检查是否有li,并根据a上的mouseenter我想触发一个事件来显示{{}} 1}}使用a,当鼠标移动到megaMenu slideDown时,我想触发next()事件。

同样,如果鼠标指向a它应该保留在屏幕上,当鼠标移动slideUp时,或者如果屏幕上没有移动,则subNavContainersubNavContainer

2 个答案:

答案 0 :(得分:0)

要选择所有li元素子元素的链接,您的选择器可能如下所示:

//select root element (`ul`), get its children (in this case the `li` elements), then get the children `a` elements of those `li` elements
$('#navRollOver').children().children('a')

然后绑定到这些元素的mouseenter事件:

//note that `.on()` is new in jQuery 1.7 and is the same in this case as `.bind()`
$('#navRollOver').children().children('a').on('mouseenter', function () {
    //do slideDown
});

然后在光标离开链接元素之后到slideUp菜单:

//you can chain function calls with jQuery functions,
//so we make our selection of the `a` elements, bind a `mouseenter` event handler to them,
//then using the same selection, we bind a `mouseleave` event handler
$('#navRollOver').children().children('a').on('mouseenter', function () {
    //do slideDown
}).on('mouseleave', function () {
    //do slideUp
});

答案 1 :(得分:0)

试试这个

var lastHoveredItem = null, hoveredOnMegaMenu = false;
$("#navRollOver > li > a").mouseenter(function(){
    hoveredOnMegaMenu = false;
    var $this = $(this);
    if(lastHoveredItem != null){
       lastHoveredItem.slideUp();
    }
    //Now based on the menu hovered you can find its its associated mega menu container
    lastHoveredItem = $(".megaMenu" + $this.attr('title')).slideDown();
})
.mouseleave(function(){
   setTimeout(function(){
      if(!hoveredOnMegaMenu && lastHoveredItem){
          lastHoveredItem.slideUp();
          lastHoveredItem = null;
      }
   });
});

//You can give megaMenu class to each of the mega menu containers so that we can 
//easily select them with class selector
$(".megaMenu").mouseenter(function(){
    hoveredOnMegaMenu = true;
})
.mouseleave(function(){
    $(this).slideUp();
    lastHoveredItem = null;
});