我想根据当前主机名在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='" + 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?
发布评论