javascript文档。编写(“”;不起作用

javascript文档。编写(“”;不起作用,javascript,Javascript,以下代码可以工作: <base href="http://www.w3schools.com/" target="_blank"> 但这不起作用: <script>document.write('<base href="' + document.location + '" />');</script> <script type="text/javascript"> document.write("<base h

以下代码可以工作:

<base href="http://www.w3schools.com/" target="_blank">    
但这不起作用:

<script>document.write('<base href="' + document.location + '" />');</script>

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

<script type="text/javascript">    
document.write("<base href="http://www.w3schools.com/" target="_blank">");    
</script>    

上,只需转义您的引用:

document.write("<base href=\"http://www.w3schools.com/\" target=\"_blank\">");    
或使用简单的引号更简单:

document.write('<base href="http://www.w3schools.com/" target="_blank">');    

你在嵌套双引号。尝试切换到单引号

<script type="text/javascript">    
document.write('<base href="http://www.w3schools.com/" target="_blank">');    
</script>    

请不要使用document.write。改用


问题是什么?不能用于设置base href。
var head = document.getElementsByTagName('head')[0]; //get the head-Element

var script = document.createElement('script'); //Create a script-element
script.setAttribute('type', 'text/javascript'); //Set an attribute

var base = document.createElement('base'); //Create a base-element
base.setAttribute('href', document.location); //Set an attribute

script.appendChild(base); //Append the base-element to the script-element
head.appendChild(script);  //Append the script-element to the head-element