给定一个锚元素(类似于
$("a:first")
),如何获得锚点指向的绝对URL?
如果您使用的是 jQuery 1.6+,则可以使用
.prop()
:
$("a:first").prop("href")
1.6 之前,您可以直接在 DOM 元素上访问
href
属性:
$("a:first")[0].href;
要获取附加的 URL,您可以执行以下操作...
var url = $("a:first").attr('href');
这将为您提供 URL,但不保证绝对或相对。
要找到绝对 URL,您可以进一步检查
if(!url.startsWith("http")) { url = "http://www.mysite.com" + url}
没有 jQuery,您可以利用普通 JavaScript:
HTMLAnchorElement: toString()
返回包含整个(“absolute”)URL的字符串:
const anchorElement = document.createElement('a');
anchorElement.href = '/help';
console.log("anchorElement object :", anchorElement);
console.log("anchorElement outerHTML :", anchorElement.outerHTML);
console.log("anchorElement toString() :", anchorElement.toString());
在此示例中,
anchorElement
使用 origin-relative URL /help
作为其 href
属性:
<a href="/help"></a>
anchorElement.toString()
返回绝对URL:
https://stacksnippets.net/help
注意:
https://stacksnippets.net/
是提供代码片段的域,this页面(stackoverflow.com)嵌入为iframe
。
var x = "http://lol.com/" + $("a:first").prop('href');
除非它是外部网址,否则应该可以工作:)