Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

javascript - .InnerHTML Not working properly in Internet Explorer

I wanted to assign a link tag to innerHTML of a HTML control. But this is not working properly in Internet Explorer. However when I try to assign anything other than <link> & <style> tags it works fine.

<html>
<head>
<script type="text/javascript">
function getValue()
  {
  var x=document.getElementById("myHeader");
  x.innerHTML='<link "http://test.com/css/template.css" rel="stylesheet"><div>abc</div>';
  alert(x.innerHTML);
  }
</script>
</head>
<body>

<h1 id="myHeader" onclick="getValue()">Click me!</h1>

</body>
</html>

Also, If I change sequence of <div> tag and <link> tag above it works fine in Internet Explorer also.

x.innerHTML='<div>abc</div><link "http://test.com/css/template.css" rel="stylesheet">';

Please suggest! Thanks.

EDIT: This is a bug in Internet Explorer with ExtJs. More information at

http://www.sencha.com/forum/showthread.php?30110-internet-explorer-autoLoad-css-not-applied

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

innerHTML won't work in IE, but using DOM methods it will:

function getValue()
{
  var x=document.getElementById("myHeader")
    , link = document.createElement('link')
    , div = document.createElement('div');
  x.innerHTML = '';
  x.appendChild(link);
  x.appendChild(div);
  div.innerHTML = 'abc';
  link.href = 'http://test.com/css/template.css';
  link.rel = 'stylesheet';
  alert(x.innerHTML);
}

Although the reference states a link tag may only appear in the header, interesting enough the style link does work if you use the code I provided, in all browsers I tried (IE, firefox, chrome). See this jsfiddle (where I used a real css-href from test.com ;-)

If you however want to place the link in it's rightful section (<head>), use:

var header = document.getElementsByTagName('head')[0];
  , link = document.createElement('link');
header.appendChild(link);
link.href = 'http://test.com/css/template.css';
link.rel = 'stylesheet';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...