根据子<a> href

时间:2016-05-06 08:42:43

标签: javascript jquery css

I have such nav stucture:

<ul class="page-sidebar-menu">
  <li class="menu">        
    <a href="">
      <span class="title">Menu Item</span>
      <span class="arrow"></span>
    </a>    
    <ul class="sub-menu">
      <li>
        <a href="somehref">Sub Menu Item</a>
      </li>
    </ul>                   
  </li>
</ul>

To highlight the submenu link I need to add active class to '.submenu li' Also I want to add active class to 'li.menu' depending on '.submenu li a' href Tried to do such like this but it's not working:

  $(function(){
    var current = location.pathname;
    current = current.substring(current.lastIndexOf('/'));
    $('.sub-menu li a').each(function(){
        var $this = $(this);
        if($this.attr('href').indexOf(current) !== -1){
            $('.sub-menu:parent').addClass('start active open'); //ISSUE
            $('.sub-menu li a:parent').addClass('active');
        }
    });

1 个答案:

答案 0 :(得分:1)

您需要使用当前迭代上下文this来定位当前锚点,并使用.closest()遍历所需的父元素.sub-menu。然后向他们添加所需的类:

 $('.sub-menu li a').each(function(){
    var $this = $(this);
    if($this.attr('href').indexOf(current) !== -1){
        $this.closest('.sub-menu').addClass('start active open'); //ISSUE
        $this.addClass('active');
    }
});