gpt4 book ai didi

javascript - 如何使用 jQuery 设计事件链接列表项的样式

转载 作者:行者123 更新时间:2023-12-01 06:25:55 26 4
gpt4 key购买 nike

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

最佳答案

this指的是 a 元素,而不是您所认为的 li 元素,它实际上是当前元素 (a) 的父元素。

您必须定位 parent()

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

或:使用 .closest()

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

关于javascript - 如何使用 jQuery 设计事件链接列表项的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60368401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com