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

如何根据当前URL为对应菜单项添加current-active-menu CSS类?

解决菜单项根据URL添加active类的问题

原代码存在两个核心问题:

  1. 硬编码完整URL进行匹配,一旦当前URL出现额外参数、参数顺序变化,就会匹配失败;
  2. 重复绑定多个document.ready事件,代码冗余。

改进方案1:灵活匹配路径与查询参数

利用URL和URLSearchParams对象解析URL,不管参数顺序、额外参数都能精准匹配:

jQuery(document).ready(function() {
  const currentUrl = new URL(window.location.href);
  const currentPath = currentUrl.pathname;
  const currentParams = new URLSearchParams(currentUrl.search);

  // 只遍历dashboard相关的菜单项
  $('a[href^="https://mywebsite.com/dashboard/"]').each(function() {
    const $link = $(this);
    const linkUrl = new URL($link.attr('href'));
    const linkPath = linkUrl.pathname;
    const linkParams = new URLSearchParams(linkUrl.search);

    // 路径匹配是基础
    if (linkPath !== currentPath) return;

    // 处理首页(无查询参数)
    if (linkParams.toString() === '') {
      if (currentParams.toString() === '') {
        $link.addClass('current-active-menu');
      }
      return;
    }

    // 处理带查询参数的页面,匹配关键参数candidate-page
    const targetParam = linkParams.get('candidate-page');
    if (targetParam && currentParams.get('candidate-page') === targetParam) {
      $link.addClass('current-active-menu');
    }
  });
});

改进方案2:简化的关键参数匹配

如果你的URL结构相对固定,也可以用更简洁的方式,只匹配关键参数部分:

jQuery(document).ready(function() {
  const currentUrl = window.location.href;

  // 匹配dashboard首页(兼容末尾有无斜杠的情况)
  if (/^https:\/\/mywebsite\.com\/dashboard\/?$/.test(currentUrl)) {
    $('a[href="https://mywebsite.com/dashboard/"]').addClass('current-active-menu');
  }

  // 匹配简历列表页
  if (currentUrl.includes('candidate-page=resumes-list')) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=resumes-list"]').addClass('current-active-menu');
  }

  // 匹配我的订单页
  if (currentUrl.includes('candidate-page=my-orders')) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=my-orders"]').addClass('current-active-menu');
  }
});

注意事项

  • 确保菜单项的href属性值和代码中的字符串完全一致(包括斜杠、参数大小写);
  • 如果网站使用相对路径(比如href="/dashboard/"),可以把代码中的完整URL替换为相对路径,提升代码通用性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:57:29