Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.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
Javascript 基于段添加活动类?_Javascript_Jquery_Substring - Fatal编程技术网

Javascript 基于段添加活动类?

Javascript 基于段添加活动类?,javascript,jquery,substring,Javascript,Jquery,Substring,我的导航中有URL,我试图根据第一段添加一个活动类,而不是绝对URL,但它不起作用 /*获取用于设置活动导航列表项的URL*/ var url=window.location.pathname.split('/') path=url[2] HTML 我试图让它将我的活动类应用于导航栏,即使url结构如下: 关于我们 关于我们/地点 关于我们/就业 如果about us在第一段中,则应应用活动类 你知道我做错了什么吗?我感谢所有的反馈 添加一个console.log(linkPath

我的导航中有URL,我试图根据第一段添加一个活动类,而不是绝对URL,但它不起作用

/*获取用于设置活动导航列表项的URL*/

var url=window.location.pathname.split('/')

path=url[2]

HTML

我试图让它将我的活动类应用于导航栏,即使url结构如下:

关于我们 关于我们/地点 关于我们/就业

如果about us在第一段中,则应应用活动类


你知道我做错了什么吗?我感谢所有的反馈

添加一个
console.log(linkPath,path)
并检查结果。@steven在上面添加了路径。谢谢@像
www.example.com/about-us
这样的AoiHana链接不起作用;使用
//www.example.com/about-us
/about-us
。此外,如果处于
http://www.example.com/about-us
location.pathname.split(“/”)[2]
将是
未定义的
;如果您想要
'about-us'
,请使用
path=url[1]
$(".navbar-nav").children("li").each(function() {
    var link = $(this).children("a").attr("href"),
        linkPathIndex = link.lastIndexOf("/")+1,
        linkPath = link.substring(linkPathIndex);

    if (linkPath == path) {
        $(this).addClass("active");
    }
});
    <ul class="nav navbar-nav">
        <li><a href="www.example.com/">Home</a></li>
        <li><a href="www.example.com/products">Products</a></li>
        <li><a href="www.example.com/services">Services</a></li>
        <li><a href="www.example.com/about-us">About Us</a></li>
    </ul>
</div>