【问题标题】:How to get "raw" href contents in JavaScript如何在 JavaScript 中获取“原始”href 内容
【发布时间】:2010-12-05 18:33:23
【问题描述】:

我正在尝试编写一个 GreaseMonkey 脚本,我想在其中找到所有相对链接的链接。在我看来,这样做的方法是将 href 的内容与 /^https?:/// 匹配。

但我发现当我访问锚的 href 属性时,它总是被规范化或煮熟成包含“http”的形式。也就是说,如果 HTML 包含:

<a id="rel" href="/relative/link">inner</a>

访问

document.getElementById("rel").href

返回

http://example.com/relative/link

如何访问 href 属性中的原始数据?

或者,有没有更好的方法来查找相对链接?

【问题讨论】:

  • 你试过 element.getAttribute("href") 吗?
  • @Ionut,你为什么不添加这个作为答案?
  • J-P,这个问题一开始有点不清楚。在我发表评论时,尚不清楚他是尝试使用 getAttribute 方法还是仅使用 href 属性。
  • 是的,我对代码大吃一惊。对不起,Ionut。

标签: javascript anchor href relative-url


【解决方案1】:

【讨论】:

  • 不幸的是,即使使用这种方法,IE7 似乎也会返回完全限定的 URL。
  • 对于那些感兴趣的人,this SO 的答案有更多关于为什么.href.getAttibute('href') 在大多数浏览器上返回不同值的信息。
【解决方案2】:

典型。发布问题后,我几乎立即就自己弄清楚了。

代替:

anchor.href

使用:

anchor.getAttribute("href")

当然,我输入这个答案比其他人回答它花费的时间更长。 (该死,你们这些人速度很快。)

【讨论】:

    【解决方案3】:

    这是一个可以运行测试的代码 sn-p。

    const anchors = document.getElementsByTagName('a');
    
    for (let anchor of anchors) {
      let hrefFullPath = anchor.href;
      let hrefRelativePath = anchor.attributes.href.value;
    
      console.log('hrefFullPath', hrefFullPath);
      console.log('hrefRelativePath', hrefRelativePath);
    }
    

    假设您在http://localhost:4200,这是您在问题中显示的文档。

    <a id="rel" href="/relative/link">inner</a>
    

    这个锚点href的属性值为:

    document.getElementById('rel').attributes.href.value => /relative/link
    

    而anchor的href值为:

    document.getElementById('rel').href =>  http://localhost:4200/relative/link
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-09
      • 2016-06-09
      • 1970-01-01
      • 2011-09-02
      • 2022-08-04
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      相关资源
      最近更新 更多