如何在Javascript中设置页面的基本href? [英] How do I set a page's base href in Javascript?

查看:112
本文介绍了如何在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.

推荐答案

这样做的正确方法是根据当前主机名做一个标签的document.write:

The correct way of doing this is to do a document.write of the tag based off the current hostname:

正确:

<script type="text/javascript">
document.write("<base href='http://" + document.location.host + "' />");
</script>

此方法在IE,FF,Chrome和Safari中产生了正确的结果。它产生(正确的)不同于下面的结果:

This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than dowing the following:

不正确:

<script type="text/javascript">
var newBase = document.createElement("base");
newBase.setAttribute("href", document.location.hostname);
document.getElementsByTagName("head")[0].appendChild(newBase);
</script>

这篇关于如何在Javascript中设置页面的基本href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆