最近做了一个网站,需要设置导航栏的act属性,这里需要用到addClass以及removeClass:

$('#topName li').removeClass('active');
$(this).addClass('active');

  但是无论怎么都没成功,后来又找到一个需要进行地址匹配一下,忘记看的哪个了,跟下面这个方法一样,就直接粘过来了(这里还有地址~~):

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
$(document).ready(function(){  
        $(".navUl li a").each(function(){  
            $this = $(this);  
            if($this[0].href==String(window.location)){   //就是这里,需要取跳转页面后的地址,但是我的地址中只要是中文就一直出现乱码
                $(".navUl li").removeClass("active");
                $this.parent().addClass("active");  //active表示被选中效果的类名   
            } 
        });  
    }); 

        原文:https://blog.csdn.net/weixin_42903350/article/details/82842081

  为了乱码,我捣鼓了一段时间,然后找到了转码的方法:

 obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);

  使用decodeURIComponent()就可以了,嗯,取地址好多方法,我看的这篇—》 直接附别人的文章https://www.cnblogs.com/cang12138/p/7677239.html

//获取当前窗口的路径
var pathname = window.location.pathname;
//结果:/Home/Index

//获取参数
var search = window.location.search;
//结果:?id=2

 

  我需要用到pathname并上search取出的地址,再进行转码,下面是我的代码:

<script type="text/javascript">
    $(function () {
        $("#topName").find("li").each(function () {
            var a = $(this).find("a:first")[0];
            var searchUrl = decodeURI(window.location.search);  //自动取当前页面的地址,这里主要是对NewsType的值进行解码
            var pathUrl = window.location.pathname + searchUrl; 
            if ($(a).attr("href") === pathUrl) 
            { 
               $(this).addClass("act"); 
            } else { 
                 $(this).removeClass("act"); 
           } 
     }); 
}) 
</script>
<div class="container" >
        <ul id="topName">
            <li class="act"><a href="/PCSite/News/NewsList?NewsType=全部" target="_top">全部</a></li>
            <li><a href="/PCSite/News/NewsList?NewsType=公告1" target="_top">公告1</a></li>
            <li><a href="/PCSite/News/NewsList?NewsType=公告2" target="_top">公告2</a></li>
            <li><a href="/PCSite/News/NewsList?NewsType=公告3" target="_top">公告3</a></li>
            <li><a href="/PCSite/News/NewsList?NewsType=公告4" target="_top">公告4</a></li>
            <li><a href="/PCSite/News/NewsList?NewsType=公告5" target="_top">公告5</a></li>
        </ul>
    </div>

 这样就能实现在页面刷新后动态添加act的功能。

 

    ps:如有侵权,请联系,立马删!

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄