[英]What is the best way to get the absolute link of an <a> tag using JavaScript/jQuery?
Getting the .href
solves the problem easy:获取
.href
可以轻松解决问题:
const a = document.getElementById("a"), b = document.getElementById("b"), c = document.getElementById("c"); console.log("A:", a.href); console.log("B:", b.href); console.log("C:", c.href);
<a href="/t/hello" id="a">A</a> <a href="hello.html" id="b">B</a> <a href="https://stackoverflow.com/testing..." id="c">C</a>
Or a pointed out by Kaiido in the comments one could use the URL constructor:或者Kaiido在评论中指出的可以使用 URL 构造函数:
const absolutePath = new URL("/absolute/or/relative/url", document.baseURI).href;
With jQuery:使用 jQuery:
const absolutePath = new URL($("a").attr("href"), document.baseURI).href;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.