Skip to main content
 首页 » 编程设计

jquery之使用 jQuery 将当前 URL 与 UL 中的 herf 进行匹配,如果匹配则添加类

2026年07月31日10jillzhang

我有一个动态创建的 UL。我想使用 jQuery 使用当前 URL,搜索指定的 UL 并找到任何具有匹配 href 的 li。如果找到,则添加“current_page”类。

我想出了这个,但似乎没有效果。

$(document).ready(function() {   
    $("ul.nav_cat_archiveli").find("a[href='"+window.location.pathname+"']").each(function() { 
        $(this).addClass("current_page"); 
    }); 
}); 

请您参考如下方法:

你可以玩window.location这将返回当前页面 URL 以及 href window.location 的属性