gpt4 book ai didi

javascript - 为什么要使用 anchor.href 属性来处理 url

转载 作者:行者123 更新时间:2023-11-30 07:53:48 25 4
gpt4 key购买 nike

我今天找到了以下代码:

var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;

其中 this.baseURL 是字符串。

它似乎利用了在设置 href 或读取 pathname 时执行的一些转换功能。这只是一个假设。这是什么功能?或者还有什么其他用途?

最佳答案

创建 anchor 并传入 URL,利用浏览器内置的 URL 解析器,因此可以轻松返回 URL 的不同部分,无需正则表达式或字符串操作。

路径名 是……好吧,协议(protocol)和主机名等之后的路径名。

一个小例子,其中一些部分可以通过这种方式返回

var baseHref = document.createElement('a');
baseHref.href = 'https://www.stackoverflow.com:3333/page/that/goes/somewhere?querystring=test#hash';

console.log('protocol : ', baseHref.protocol);
console.log('host : ', baseHref.host);
console.log('hostname : ', baseHref.hostname);
console.log('port : ', baseHref.port);
console.log('pathname : ', baseHref.pathname);
console.log('querystring : ', baseHref.search);
console.log('hash : ', baseHref.hash);

这实际上只是使用浏览器解析 URL 的巧妙技巧。

关于javascript - 为什么要使用 anchor.href 属性来处理 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com