2013-01-16 38 views
1

我已经基本上得到了这个标记:巢LI功能

<div class="navBar"> 
    <div class="inner blueTheme"> 
    <ul id="" class="navBarMenu"> 
     <li class="xenonActiveMenu blue"><a href="/new_order">Orders</a> 
     <ul> 
      <li class="backBtn"><a href="#">&lt; Back</a> 
      </li> 
      <li class="xenonActiveMenu "><a href="/new_order">New Order</a> 
      </li> 
     </ul> 
     </li> 
     <li class="green"><a href="/account_details">Profile</a> 
     <ul> 
      <li class="backBtn"><a href="#">Back</a> 
      </li> 
     </ul> 
     </li> 
     </ul> 
    </div>  
</div> 

的Jquery:

$('.navBar .inner ul > li').bind('click', function(e){ 
    e.preventDefault(); 
    item = $(this); 
    if (item.attr('class') != 'selected' && item.attr('class') !='backBtn') { 
     item.addClass('selected'); 
     var parent = item.parent(); 
     var barWidth = item.width(); 
     var hasSub = item.find('ul').length; 
     if (hasSub > 0){ 
     //Item Does have a submenu 
     parent.children().each(function(){ 
      $(this).animate({marginLeft: -barWidth}, 400); 
     }); 
     } 
    } else { 
     var parent = $(this).parent().closest('li'); 
     var barWidth = $(this).width(); 
     parent.each(function(){ 
     $(this).animate({marginLeft: barWidth}, 400); 
     }); 
    } 
    }); 

我的问题是,它认为“礼”元素已经被点击了两次,监守有两家单独的嵌套LI元素的函数,我只是不知道它的方式,任何人都可以帮忙吗?

+0

可能是您应该取消冒泡事件以避免该事件被运行两次。 if(event.stopPropagation){event.stopPropagation(); }(对于firefox和webkit)和event.cancelBubble = true; (用于IE) – MatRt

+0

@ user1073122 jQuery将处理jQuery封装的事件对象上的['event.stopPropagation()'](http://api.jquery.com/event.stopPropagation/)的规范化。你应该提交这个答案。 –

回答

1

使用stopPropagation,这不正是它的名字所暗示的:它会阻止事件的DOM树冒泡到<li>元素的一个新的水平。

或者,您可以分开您的处理程序以使代码更具可读性,第一级使用$('.navBar .inner > ul > li'),第二级使用$('.navBar .inner > ul > li ul li')

使用stopPropagation更新的代码如下所示。

$('.navBar .inner ul > li').click(function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 

    // your code for handler 
});