如何基于当前url添加类

How to add class based on current url

本文关键字:添加 url 何基于      更新时间:2023-09-26
var search_name = location.search;
    if (search_name.search("cate_no=24")  > 0) {
        $(".cate_new a").addClass("active");
    }
});

如果当前文档的url是http://abc.com/list.html?cate_no=24,我想添加类"active"到li a.

我搜索并找到了这些js代码,但它不起作用。这有错吗?

不正确。 search() 返回匹配的偏移位置,如果找到匹配,则返回-1

当您检查cate_no=24是否包含cate_no=24时,如果为真,它将返回0

目前,您的条件检查search()是否会返回> 0,这不是您想要的。

你应该做的是检查它是否大于> -1:

if (search_name.search("cate_no=24") > -1) 

虽然,正如我在回答的第一次修订中提到的,使用 indexOf() 会更好更快(search()应该在处理正则表达式时使用,而不是用于简单的字符串搜索)。

if (search_name.indexOf("cate_no=24") > -1) 

search只会给你字符串。?cate_no=24

因此,我们保留第一部分,并尝试在search_name中找到所需的值作为字符串。

var search_name = location.search;

这就是我们如何找到所需模式的索引。

if (search_name.indexOf("cate_no=24") > 0) {
    $(".cate_new a").addClass("active");
}

我的个人博客是静态的,所以我也不得不弄清楚如何做到这一点没有PHP或其他一些服务器端代码。

这段代码捕获当前URL的路径,例如,如果您在http://example.com/about上,它将返回字符串'/about/'。从这里,您可以编写一个简单的条件,将一个类添加到您选择的链接中。

var currentURL = window.location.pathname.toString();
console.log(currentURL);
if (currentURL = '/about/') { 
    $('a#about').addClass('active')
} else if (currentURL = '/work/') {
    ...
}

可以进一步开发,以便从具有特定类(例如.nav-items)的链接数组中获取href属性,并将活动类添加到具有等于返回字符串的href的任何元素中。