简体   繁体   English

<a>使用 JavaScript/jQuery 获取标签的绝对链接的最佳方法是什么?</a>

[英]What is the best way to get the absolute link of an <a> tag using JavaScript/jQuery?

HTML: HTML:

<a href="3.html">No. 3</a>

JS: JS:

$('a').attr('href') // would return the string "3.html"

How can I get the string of the full path:如何获取完整路径的字符串:

$('a').fullLinkAttr('href') // returns https://www.example.com/3.html

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.

相关问题 使用javascript或jquery用GET参数组成链接的最佳方法是什么 - What is the best way to compose a link with GET parameters using javascript or jquery 使用 jQuery 使这些数据持久保存在 Javascript 事件处理程序中的最佳方法是什么 - What's the best way to get this data to persist within Javascript event handlers using jQuery 使用JavaScript或Jquery在浏览器中存储本地值的最佳方法是什么? - what is the best way to store local values in browser using Javascript or Jquery? 使用javascript / jquery,更新设置图像的src的最佳方法是什么? - Using javascript/jquery, what is the best way to update the src of a set images? 使用 javascript/jQuery 实现多路切换的最佳方法是什么? - What is the best way to implement multiway toggle using javascript/jQuery? 在 JavaScript 中简化对象的最佳方法是什么(最好使用 Jquery) - What is the best way to simplify Objects in JavaScript (perferably using Jquery) 在JavaScript中计算绝对数组长度的最佳方法是什么? - What is the best way to count absolute array length in JavaScript? 使用JavaScript获取和设置单个cookie值的“最佳”方法是什么? - What is the “best” way to get and set a single cookie value using JavaScript 链接到javascript的最佳方法 - Best way to link to javascript 在JavaScript中获取随机数的最佳方法是什么 - What is the best way to get random number in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM