Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery“;主动”;父类的类赋值_Jquery - Fatal编程技术网

jQuery“;主动”;父类的类赋值

jQuery“;主动”;父类的类赋值,jquery,Jquery,我的主导航中有以下html: <div id="navigation"> <ul> <li> <a href="/contact">contact us</a> </li> <li> <a href="/projects">projects</a> </li> </ul> <

我的主导航中有以下html:

<div id="navigation">  
  <ul>
     <li>
       <a href="/contact">contact us</a>
     </li>
   <li>
      <a href="/projects">projects</a>       
   </li>
  </ul>
 </div>
虽然它对像domain.com/projects或domain.com/contacts这样的URL很有用,
我对deepers URL有一个问题,以domain.com/projects/proj-1为例。
我希望当我转到更深的URL时,它会将父URL(domain.com/projects)标记为活动的。我该怎么做

谢谢

您可以使用jquery的操作符向上遍历树并标记所有父lis。像这样

$(this).closest("li","#navigation").addClass("active");    
“最近”比“父母”更有效,因为您可以将搜索限制在菜单的上下文中

另外,作为旁白,您不需要进行循环。您可以这样做:

$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active");
因此,您的整个代码应该如下所示:

$selected = $("div#navigation").find("a[href='" + top.location.pathname + "']");
$selected.addClass("active");
$selected.closest("li","#navigation").addClass("active");

首先,在您的示例中,您不必使用
.each()
方法,因为您可以像这样直接分配类

$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active")
针对问题使用

$("div#navigation").find("a").filter(function(){
    var href =  $(this).attr('href');
    return href!='/' && href !='#' && top.location.pathname.indexOf( href )==0 ;
}).addClass("active");

编辑:对注释问题做了一个小改动

代码现在正在运行,但它仍然没有解决我的问题-当我处于2级链接(/projects/proj-1等)时,它仍然没有用活动类标记家长李,这感谢它看起来不错-一个问题:它总是将主页(href='/')李也标记为活动
$("div#navigation").find("a").filter(function(){
    var href =  $(this).attr('href');
    return href!='/' && href !='#' && top.location.pathname.indexOf( href )==0 ;
}).addClass("active");