获取URL路径并在li上添加活动类 [英] Get url path and add class active on li

查看:122
本文介绍了获取URL路径并在li上添加活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试获取url路径,然后在li上添加活动类 例子: www.mysite.com/?p=xxxx

I try to grab the url path and then add active class on li example: www.mysite.com/?p=xxxx

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

the x will change depending on which link the user clicks on

我尝试过:

<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");

但是什么也没发生.我在做什么错了?

but nothing happens. What im i doing wrong?

推荐答案

这有效!

$(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");

        }

    });

});

这篇关于获取URL路径并在li上添加活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆