Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获得;生的;JavaScript中的href内容_Javascript_Anchor_Href_Relative Url - Fatal编程技术网

如何获得;生的;JavaScript中的href内容

如何获得;生的;JavaScript中的href内容,javascript,anchor,href,relative-url,Javascript,Anchor,Href,Relative Url,我正在尝试编写一个GreaseMonkey脚本,其中我希望找到所有相对链接。在我看来,这样做的方法是将href的内容与/^https?://相匹配 但我发现,当我访问锚的href属性时,它总是被规范化或被制作成一个包含“http”的表单。也就是说,如果HTML包含: <a id="rel" href="/relative/link">inner</a> 返回 http://example.com/relative/link 如何访问href属性中的原始数据 或者,有没

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

但我发现,当我访问锚的href属性时,它总是被规范化或被制作成一个包含“http”的表单。也就是说,如果HTML包含:

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

http://example.com/relative/link
如何访问href属性中的原始数据


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

试试典型的。发帖后,我几乎马上就明白了

<a id="rel" href="/relative/link">inner</a>
而不是:

anchor.href
使用:


当然,我输入这个答案的时间比其他人回答的时间要长。(该死,你们太快了。)

这里有一段代码片段,可以运行测试

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').href =>  http://localhost:4200/relative/link

我希望这会有帮助。

你试过element.getAttribute(“href”)?@Ionut,你为什么不加上它作为答案呢?J-p,问题一开始有点不清楚。在我发表评论时,不清楚他是尝试使用
getAttribute
方法还是仅使用
href
属性。是的,我对代码进行了大量的讨论。抱歉,Ionut。不幸的是,即使采用这种方法,IE7似乎也会返回完全限定的URL。对于那些感兴趣的人,answer提供了更多信息,说明为什么
.href
.getAttibute('href')
在大多数浏览器上返回不同的值。
document.getElementById('rel').attributes.href.value => /relative/link
document.getElementById('rel').href =>  http://localhost:4200/relative/link