如何根据当前URL为对应菜单项添加current-active-menu CSS类?
解决菜单项根据URL添加active类的问题
原代码存在两个核心问题:
- 硬编码完整URL进行匹配,一旦当前URL出现额外参数、参数顺序变化,就会匹配失败;
- 重复绑定多个
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
相关产品推荐
相关产品推荐

