JavaScript如何匹配任意href链接实现侧边栏激活功能
侧边栏普通路径匹配失效修复
问题根源
原有代码逻辑只针对哈希路由(带#的链接)设计:
- 仅读取
window.location.hash作为匹配依据,非哈希链接的路径信息完全没被获取 - 哈希值为空时直接终止执行,普通路径场景下函数直接退出不运行
- 仅监听
hashchange事件,普通路径跳转、页面刷新时不会触发匹配逻辑
修改点说明
- 替换取值逻辑:读取
window.location.pathname作为当前页面路径匹配值,如果需要匹配带查询参数的路径可以拼接window.location.search - 删除哈希为空直接返回的判断
- 新增
popstate事件监听,适配history模式路由的路径切换场景 - 保留原有侧边栏展开、激活态切换的逻辑不变,兼容原有哈希路由场景
修改后完整代码
<script> (() => { 'use strict' function setActiveItem() { // 取当前页面路径,需要匹配带查询参数的场景可改为 const currentPath = window.location.pathname + window.location.search const currentPath = window.location.pathname // 匹配href和当前路径一致的侧边栏链接 const link = document.querySelector(`.d-flex a[href="${currentPath}"]`) if (!link) { return } const active = document.querySelector('.d-flex .active') const parent = link.parentNode.parentNode.previousElementSibling link.classList.add('active') if (parent.classList.contains('collapsed')) { parent.click() } if (!active) { return } const expanded = active.parentNode.parentNode.previousElementSibling active.classList.remove('active') if (expanded && parent !== expanded) { expanded.click() } } setActiveItem() // 监听history路由变化,多页场景下保留这行也不会有负面影响 window.addEventListener('popstate', setActiveItem) // 兼容原有哈希路由场景 window.addEventListener('hashchange', setActiveItem) })() </script>
注意:如果项目里a标签的href写的是带域名的完整地址,可以在匹配时对比
link.pathname和当前页面pathname,避免域名、协议差异导致匹配失败。
内容的提问来源于stack exchange,提问作者mario7111
相关产品推荐
相关产品推荐

