如何在Javascript中设置页面的基本href?

编程入门 行业动态 更新时间:2024-10-20 21:00:37
本文介绍了如何在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='" + 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?

本文发布于:2023-10-08 01:35:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:页面   如何在   Javascript   href

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!