首页 > 解决方案 > 如何使用 jQuery 设置活动链接列表项的样式

问题描述

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

标签: javascriptjqueryhtmlcssdom

解决方案


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

您必须针对parent()

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

或:使用.closest()

$this.closest('li').addClass('active');

推荐阅读