设置Active Link jQuery

时间:2011-09-20 23:22:37

标签: jquery navigation

我的网站上有这样的链接结构......

index.php - homepage
index.php?section=  - other pages

这是我写的一段代码,用于更改活动链接的颜色......

$(function(){
     var path = location.pathname.substring(1);
     if ( path )
          $('#nav ul#navigation li a[href$="' + path + '"]').attr('class', 'selected');
});

但这没有考虑PHP链接结构,只考虑平面文件链接。如何使用index.php?section=等链接以及index.php等基本链接?

2 个答案:

答案 0 :(得分:0)

使用类名而不是完整的URL。它让它变得不那么罗嗦了。

var path = document.location+""
path = path.split("?section=")
if(path.length>1) {
      $("."+path[1]).addClass('selected')
}

然后在你的html:

<a class="section">...</a>
<a class="otherSection">...</a>

如果你想要更少的网址依赖,你可以使用哈希:

网址:http://yoursite.com?blabblah=xxx....#section1

然后使用document.location.hash(将=“section1”)作为节指示符。它为您节省了解析URL的步骤。

答案 1 :(得分:0)

您可以尝试剥离index.php?section =并使用包含选择器(* =)。

$(function() {
    var path = location.pathname.substring(1);

    if ( path.indexOf('?section=') ) {
        path = path.replace('index.php?section=', '');
    }

    if ( path )
        $('#nav ul#navigation li a[href*="' + path + '"]').attr('class', 'selected');
    }
});