获取url路径并在li上添加活动类

Kas*_*per 0 url jquery addclass path href

我尝试抓住url路径,然后在li示例中添加活动类:www.mysite.com/?p = xxxx

x将根据用户点击的链接而改变

我试过这个:

<ul class="top_menu">
<li class="tider"><a href="/?p=1884">Åbningstider</a></li>
<li class="butikker"><a href="/?p=1885">Butikker</a></li>
<li class="sker"><a href="/?p=1886">Det sker</a></li>
<li class="nyhedsbrev"><a href="/?p=1887">Nyhedsbrev</a></li>
<li class="vej"><a href="/?p=1888">Find vej</a></li>
</ul>

var text = window.location.href.match(/http:\/\/www\.mysite\.com\/(.+)/)[1].replace(/_/g,' ');
$("#nav li").filter(function() {
  return $.text([this]) == text;
}).addClass("active");
Run Code Online (Sandbox Code Playgroud)

但没有任何反应.我做错了什么?

Kas*_*per 7

这有效!

$(document).ready(function(){

    var full_path = location.href.split("#")[0];

    $(".top_menu li a").each(function(){

        var $this = $(this);

        if($this.prop("href").split("#")[0] == full_path) {

            $(this).parent().addClass("active");

        }

    });

});
Run Code Online (Sandbox Code Playgroud)