javascript - 如何使用 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');
}
})
})
解决方案
this
指的是a元素而不是li您正在考虑的实际上是当前元素 ( a ) 的父级。
您必须针对parent()
$this.parent().addClass('active');
或:使用.closest()
$this.closest('li').addClass('active');
推荐阅读
- python-3.x - 如何将python文件的if __name__ =='__main__'中的变量导入其他python文件?
- java - 如何理解这个产生 DOM 输出的 Java 代码?
- github - 有没有办法设置 GitHub 问题编号?
- c# - EF Core延迟加载极慢
- java - 赋值时,Java 给出错误“java:
预期',为什么? - android - 使用 jar 库的 android 应用程序中的电子邮件传递问题
- javascript - Jquery listview不附加样式表
- javascript - THREE.Audio - 获取 currentTime 并设置 onEnded 函数
- python - pytz - 时区偏移量与公开信息不一致
- node.js - 在 Heroku 上部署 Vue 应用程序时出现意外的语法错误