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

Dan*_*Dan 5 jquery

我有一个动态创建的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");
    });
});
Run Code Online (Sandbox Code Playgroud)

Amr*_*rhy 1

您可以使用window.location ,它将返回当前页面 URL 以及window.location 的href属性