如何使用jQuery设置活动链接列表项的样式

问题描述 投票:0回答:1

[我正在使用jQuery来检查浏览器的URL是否与我的链接href中的URL匹配,问题出在我检查之后,我试图将链接匹配的li标记类设置为“活动”,但是下面的这段代码是将链接标签设置为活动标签而不是li标签

    $(function(){
        var current = location.pathname;
        $('#nav li a').each(function(){
            var $this = $(this);
            // if the current path is like this link, make it active
            if($this.attr('href') === current){
                $this.addClass('active');
            }
        })
    }) 

javascript jquery html css dom
1个回答
2
投票

this是指a元素,而不是您正在考虑的li,它实际上是当前元素(a)的父元素。

您必须指定父母:

this
© www.soinside.com 2019 - 2024. All rights reserved.