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

如何使用jQuery移除指向当前网页URL的导航链接的href属性

你之前的代码无法生效,核心原因是window.location.href返回的是带域名、协议的完整绝对URL(比如https://wordsbyfarber.com/en/ws/android),而你导航栏里的href属性写的是相对根路径的地址,两者字符串完全不一致,自然无法匹配到对应元素。

推荐遍历导航下的所有链接,统一把路径转成标准格式后再匹配,天然兼容相对路径、绝对路径两种写法,代码如下:

$(document).ready(function() {
  // 取当前页面的路径部分,自动排除域名、锚点、查询参数干扰
  const currentPagePath = window.location.pathname;
  // 遍历导航下所有链接
  $('#navigation a').each(function() {
    // 统一把链接地址转成标准路径格式
    const linkPath = new URL($(this).attr('href'), window.location.origin).pathname;
    // 路径匹配则移除href属性
    if (linkPath === currentPagePath) {
      $(this).removeAttr('href');
      // 可选:添加激活样式类,方便自定义当前页导航的视觉效果
      // $(this).addClass('current-nav-item');
    }
  });
});

如果你的导航链接可能带查询参数需要一起匹配,只需要调整对比逻辑即可:

$(document).ready(function() {
  const currentFullPath = window.location.pathname + window.location.search;
  $('#navigation a').each(function() {
    const linkUrl = new URL($(this).attr('href'), window.location.origin);
    const linkFullPath = linkUrl.pathname + linkUrl.search;
    if (linkFullPath === currentFullPath) {
      $(this).removeAttr('href');
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:24:00