
本文介绍一种健壮的 jQuery 方案,通过提取当前 URL 的文件名(不含查询参数),匹配 元素的 data-target 属性,实现精准、稳定的导航高亮,即使 URL 含 ?page=2 或 &id=1 等参数也不失效。
本文介绍一种健壮的 jquery 方案,通过提取当前 url 的文件名(不含查询参数),匹配 `
在实际开发中,常见的导航高亮逻辑往往直接比对完整 URL(如 this.href == window.location.href),但该方式对带查询参数(如 sub01.html?page=2)或锚点(如 sub01.html#section)的 URL 失效——因为 href 值不完全相等。而本方案采用语义化匹配:以 data-target 为唯一标识,依据当前页面路径的 basename(即文件名)进行模糊匹配,既保持语义清晰,又具备强兼容性。
✅ 正确实现逻辑
核心思路是:
- 从 window.location.pathname 中提取最后一级路径(如 /link/sub01.html → sub01.html);
- 截取文件名主体(去掉 .html 等扩展名),得到 sub01;
- 查找所有
- 中 data-target="sub01" 的元素,并为其添加 active 类。
以下是优化后的完整脚本(含健壮性增强):
$(document).ready(function() {
// 获取 pathname 并安全提取 basename(兼容 /sub01、/sub01.html、/dir/sub01.html)
const path = window.location.pathname;
const basename = path.split('/').pop(); // 如 "sub01.html" 或 "sub01"
const targetKey = basename.replace(/\.[^/.]+$/, ''); // 移除扩展名,得 "sub01"
// 匹配 data-target 等于 targetKey 的 li 元素,并添加 active
$('#Nav .Cate li[data-target="' + targetKey + '"]').addClass('active');
// 可选:同时移除其他 li 的 active 类,确保单激活态
$('#Nav .Cate li').not('[data-target="' + targetKey + '"]').removeClass('active');
});
⚠️ 注意事项与最佳实践
- 不要依赖 href 属性匹配:原始代码中 a[href="..."] 易受路径写法(相对/绝对)、编码(&)、查询参数干扰,应改用 data-target 这一语义化属性作为唯一标识。
- 避免硬编码扩展名:使用正则 /\.[^/.]+$/ 安全移除任意扩展名(.html/.php/.htm),而非简单 substring(0, -5)。
-
优先操作
- 而非
:CSS 样式定义在 .Cate li.active 上,直接对 li 添加类更符合结构逻辑,也避免嵌套 .parent().addClass() 的冗余链式调用。 - 注意 HTML 中 & 是实体编码:浏览器解析后 &page=2 实际为 &page=2,不影响 pathname 提取(pathname 不含查询字符串),因此无需特殊处理。
✅ 最终 HTML 结构建议(保持语义一致)
<div id="Nav">
<ul class="Cate">
<li data-target="index"><a href="index.html">MAIN</a></li>
<li data-target="sub01"><a href="sub01.html">SUB01</a></li>
<li data-target="sub02"><a href="sub02.html">SUB02</a></li>
</ul>
</div>
只要当前 URL 的路径末尾为 index.html、sub01.html?page=2、sub02.html#top 或 ./sub01.html,脚本均能准确激活对应 data-target 的











