javascript document.write(&#34; <base href =“”/>&#34;);不工作

时间:2015-01-08 15:51:40

标签: javascript

以下代码有效:

<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>    

http://www.customtemplates.com.au/

3 个答案:

答案 0 :(得分:1)

只是逃避你的报价:

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

使用简单的引号更简单:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:-1)

请不要使用document.write。请改用createElement

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