根据当前URL为链接添加active类报each非函数错误解决方法
报错原因
document.querySelectorAll() 返回的是原生 NodeList 集合,不存在jQuery对象才有的.each()方法,同时你的代码里混用了jQuery的.attr()方法和原生DOM的classList API,语法不统一也是潜在问题。
最小修复代码
直接把jQuery风格的遍历和方法替换成原生DOM API即可正常运行:
const current = window.location.href; document.querySelectorAll("#nav-tab a").forEach(function(el){ if(el.href.includes(current)){ el.classList.add("active"); } });
更稳妥的优化方案
直接用完整window.location.href做字符串匹配很容易出现误判,比如根路径/会匹配站内所有链接、带查询参数/锚点的URL会匹配失败,建议改成匹配路径名、提前清空旧高亮状态的实现:
// 提取当前页面路径,忽略域名、查询参数、锚点干扰 const currentPath = window.location.pathname; const navLinks = document.querySelectorAll("#nav-tab a"); // 先清空所有导航链接的active状态,避免多链接同时高亮 navLinks.forEach(link => link.classList.remove("active")); navLinks.forEach(link => { // 统一解析链接路径,消除相对路径、绝对路径的写法差异 const linkPath = new URL(link.href, window.location.origin).pathname; // 做精准路径匹配,避免短路径误匹配长路径 if(linkPath === currentPath) { link.classList.add("active"); } });
如果你的项目里已经引入了jQuery,也可以统一用jQuery写法避免原生和jQuery语法混用:
const currentPath = window.location.pathname; const $navLinks = $("#nav-tab a"); $navLinks.removeClass("active"); $navLinks.each(function(){ const $this = $(this); const linkPath = new URL($this.attr("href"), window.location.origin).pathname; if(linkPath === currentPath) { $this.addClass("active"); } });
内容的提问来源于stack exchange,提问作者ddd
相关产品推荐
相关产品推荐

