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

使用jQuery将当前URL与UL中的herf匹配,如果匹配,则添加类,jquery,Jquery,我有一个动态创建的UL。我想使用jQuery来使用当前URL,搜索指定的UL并找到任何具有匹配href的li。如果找到一个,则添加类“当前页面” 我想出了这个办法,但似乎没用 $(document).ready(function() { $("ul.nav_cat_archiveli").find("a[href='"+window.location.pathname+"']").each(function() { $(this).addClass("current_

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

我想出了这个办法,但似乎没用

$(document).ready(function() {  
    $("ul.nav_cat_archiveli").find("a[href='"+window.location.pathname+"']").each(function() {
        $(this).addClass("current_page");
    });
});
您可以使用它来返回当前页面URL以及窗口的属性。位置


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var windowLocationPathname = "/HTMLPage16.htm";  // For testing purpose.

            //Or

            //var windowLocationPathname = window.location.pathname;

            $('ul.nav_cat_archiveli').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage');
        });
    </script>
    <style type="text/css">
        .nav_cat_archiveli
        {
            list-style: none;
        }

        a.currentPage
        {
            color: Red;
            background-color: Yellow;
        }
    </style>
</head>
<body>
    <ul class="nav_cat_archiveli">
        <li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li>
        <li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li>
        <li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li>
        <li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li>        
    </ul>
</body>
</html>
$(文档).ready(函数(){ var windowLocationPathname=“/HTMLPage16.htm”;//用于测试目的。 //或 //var windowLocationPathname=window.location.pathname; $('ul.nav_cat_archiveli').find('a[href^=“”+windowLocationPathname+'”).addClass('currentPage'); }); .nav_cat_archiveli { 列表样式:无; } a、 当前页 { 颜色:红色; 背景颜色:黄色; }

太棒了!一定是有史以来最快的答案!我将.pathname更改为.href,它完全按照要求工作。谢谢。document.location.pathname为我工作。window.location.href没有。(var windowLocationPathname=“/HTMLPage16.htm”)。此行仅用于测试。请删除该行并使用(var windowLocationPathname=window.location.pathname;)