You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为侧边栏激活URL对应链接添加active类

侧边栏激活链接自动添加active类失效修复

原有问题代码

const address = location.pathname;
const links = document.querySelectorAll('.sidebarMain a');

links.forEach(function(el) {
 if(new RegExp(`^${el.getAttribute('href')}(.*)$`, 'i').test(address))
el.classList.add('active')});

失效原因

  • 没有转义正则特殊字符:直接将href属性值拼接进正则表达式时,如果href包含.、?、+这类正则元字符,会导致匹配逻辑完全错乱,无法得到预期结果。
  • 路径格式不统一:location.pathname返回的路径始终以/开头,但a标签的href可能写为相对路径(不带开头/),也可能存在尾部多余斜杠,两边格式不一致时会直接匹配失败。
  • 匹配规则不严谨:原有规则只要前缀匹配就加类,侧边栏同时存在父子层级链接时(比如/doc和/doc/list),会误给父级链接也加上active类;另外没有做空值判断,遇到没有href属性的a标签会直接抛错中断执行。
  • 执行时机/选择器错误:如果脚本在DOM加载完成前执行,或者.sidebarMain a选择器和实际页面类名不匹配,根本拿不到目标链接节点,逻辑自然不会生效。

修正后可直接用的代码

// 等DOM完全加载后再执行逻辑
document.addEventListener('DOMContentLoaded', () => {
  const currentPath = location.pathname;
  const sidebarLinks = document.querySelectorAll('.sidebarMain a');

  // 转义正则特殊字符
  const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  // 标准化路径格式:统一开头斜杠,去除尾部多余斜杠
  const normalizePath = (path) => {
    if (!path) return '';
    let p = path.trim();
    if (!p.startsWith('/')) p = `/${p}`;
    return p.replace(/\/+$/, '');
  };

  const standardCurrentPath = normalizePath(currentPath);

  sidebarLinks.forEach(link => {
    const linkHref = link.getAttribute('href');
    if (!linkHref) return;
    const standardLinkPath = normalizePath(linkHref);
    // 匹配规则:路径完全相等,或者当前路径是链接路径的子页面
    const matchRule = new RegExp(`^${escapeRegExp(standardLinkPath)}(\\/.*)?$`, 'i');
    if (matchRule.test(standardCurrentPath)) {
      link.classList.add('active');
    }
  });
});

额外排查点

  • 如果页面链接带查询参数,可以把currentPath的取值换成location.pathname + location.search,避免参数导致匹配失效。
  • 如果需要精确匹配完全相等的路径,直接把正则判断改成standardCurrentPath === standardLinkPath即可。

内容的提问来源于stack exchange,提问作者YOKA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:15:41