Javascript:如何为引用另一个域的 URL 使用 setAttribute "href"

Javascript: How to use setAttribute "href" for a URL refering to another domain

在我的 html 代码中,我使用了带有空 <href><a> 标签,因为 url 一开始是未知的。

假设现在有一个新目标 "www.amazon.de"。 现在我尝试用 javascript:

更改 href
document.getElementById('linkname').setAttribute("href", "www.amazon.de");

但我的浏览器只为我的域创建一个相对 link,如下所示:

https://www.mydomain.de/www.amazon.de>

(如果我将鼠标悬停在 link 上就会显示)

您必须将协议 ('https://') 添加到 link:

document.getElementById('linkname').setAttribute("href", "https://www.amazon.de");

那是因为www.amazon.de的亲戚link。要 link 不同的域(主机),您需要以双斜杠 authority component 开头://www.amazon.de,或使用包含的方案 https://www.amazon.de.

您似乎缺少 'http://' 或 'https://'