Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.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向导航添加活动css类_Jquery_Css - Fatal编程技术网

使用jQuery向导航添加活动css类

使用jQuery向导航添加活动css类,jquery,css,Jquery,Css,大家好,我正在寻找一种简单、不引人注目的方法,根据目录将class=“active”添加到无序列表菜单中。不幸的是,我无法将自定义类添加到body标记中,因此无法使用纯css解决方案 有谁能给我推荐一个好的教程吗?我已经看过了,但是找不到一个适合我需要的。代码如下所示,我只需要添加基于/directory/或/a的类,jquery解决方案将是理想的,因为我已经加载了jquery库 <ul class="nav"> <li><a href="/index.html"&

大家好,我正在寻找一种简单、不引人注目的方法,根据目录将class=“active”添加到无序列表菜单中。不幸的是,我无法将自定义类添加到body标记中,因此无法使用纯css解决方案

有谁能给我推荐一个好的教程吗?我已经看过了,但是找不到一个适合我需要的。代码如下所示,我只需要添加基于/directory/或/a的类,jquery解决方案将是理想的,因为我已经加载了jquery库

<ul class="nav">
<li><a href="/index.html">Home</a></li>
<li><a href="/about/about.html">About Us</a></li>
<li><a href="/cv/submit-your-cv.html">Submit CV</a></li>
<li><a href="/vacancies/index.html">Vacancies</a></li>
<li><a href="/news/news.html">Company News</a></li>
<li><a href="/praise/praise.html">Praise</a></li>
<li class="nosep"><a href="/contact/contact.html">Contact Us</a></li>
</ul>

您可以查看window.location变量并为每个li元素设置一个id。然后是:

$("...").addClass("myCssClass");
希望它在某些方面有所帮助…

尝试以下方法:

$(".nav li:has(a[href$='"+window.location.pathname+"'])").addClass("active");

希望这有助于你的概念将有一个输出 在上更改每个特定页面的颜色

var wo=window.location.pathname

jQuery(“ul.nav li a”)。每个(函数(){ var thisvar=jQuery(this); var ifid=jQuery(this.attr(“href”)

} });


如果你喜欢这篇文章,你也可以在

Hi Nick上访问它,这很好,但它在索引页上似乎失败了?有什么想法可以让它工作吗?问题似乎是,当用户访问/而不是/index.html时,活动类不会出现。此外,如果任何其他页面被称为index.html,脚本将复制活动类。@toomanyairmiles-将URL设为绝对选项,或者你知道完整路径是什么吗?我可以在一些菜单中放置绝对URL,但有些部分是博客,它们需要从根目录继承类。@toomanyairmiles-如果你的站点是根目录,那么你可以去掉
$=
,替换为
=
,从“以结尾”改为“以结尾”对于一个相等的计划,看看这是否符合你的要求…在不知道你的布局的情况下,我无法确切地说。
if(ifid == wo){

         switch(ifid){
          case "/index.html":
            thisvar.css("color","#000000");
          break;
          case "/about/about.html":
           thisvar.css("color","#EE2E24");
          break;

}