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

Cod*_*Bae 1 html javascript css jquery dom

我正在使用 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');
            }
        })
    }) 

Run Code Online (Sandbox Code Playgroud)

Mam*_*mun 5

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

你必须针对 parent()

$this.parent().addClass('active');
Run Code Online (Sandbox Code Playgroud)

或:使用.closest()

$this.closest('li').addClass('active');
Run Code Online (Sandbox Code Playgroud)