如何在 Javascript 中设置页面的基本 href?
我想根据当前主机名在 Javascript 中设置页面的基本 href 属性。我已经生成了可以在不同主机名上查看的 HTML 页面,这意味着生成基本 href 标签在一个主机名中可以工作,但在另一个主机名中则不正确。
I want to set a page's base href attribute in Javascript based off of the current hostname. I have generated HTML pages that can be viewed on different hostnames, which means generating a base href tag will work in one hostname but will be incorrect in the other.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正确的方法是根据当前主机名对标记执行 document.write:
正确:
此方法在 IE、FF、Chrome 和 Safari 中产生了正确的结果。它产生的(正确的)结果与执行以下操作不同:
不正确:
The correct way of doing this is to do a document.write of the tag based off the current hostname:
Correct:
This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than doing the following:
Incorrect:
我认为你最好这样做,
因为
location.hostname
不会返回应用程序上下文根!您还可以在控制台console.log
上记录document.location
,以查看document.location
上的所有可用元数据。I think you'd better do it this way
As
location.hostname
does not return the application context root! You could also log thedocument.location
on the consoleconsole.log
to see all available metadata ondocument.location
.我不得不不同意最上面的答案。它不考虑协议,因此会失败。
我必须考虑协议/主机/端口的工作解决方案如下,
目前在包括 IE11 在内的所有主要浏览器中都可以正常工作
我已经使用它来制作一个 npm 包,该包还支持在该基本 href 的末尾添加后缀如果任何人都感兴趣
https://www.npmjs.com/package/dynamic-base
https://github.com/codymikol/dynamic-base
I have to disagree with the top answer. It does not account for the protocol so it will fail.
A working solution that I have to account for protocol / host / port is the following
This currently works fine in all major browsers including IE11
I have used this to make an npm package that also supports adding a suffix to the end of this base href if anyone is interested
https://www.npmjs.com/package/dynamic-base
https://github.com/codymikol/dynamic-base
document.write("");
document.write("");
href 变量是您要使用的 href。
The href variable is the href you want to use.