开发者

innerHTML doesn't function correctly in IE

I am trying to populate a div using innerHTML, which works fantastically under all browsers except IE (specifically being tested under 8 and 9). I can find lots of information on this topic, but no simple answers. It seems to sometimes work if I don't have any tags in the text, but never with. Can anyone help me understand the problem, and potential workarounds for this?

<html>
<body>

    The following box should contain text populated with innerHTML开发者_高级运维,
    but doesn't in IE
    <p id="inner" style="width:250px; height: 100px;  margin: 20px auto; background-color: #fff; border:5px solid orange; padding:7px; text-align:left; }"></p>

    <script type="text/javascript">
        var txt = "<h1>Just a quick test!</h1>"  
        var inner = document.getElementById("inner");
        inner.innerHTML=txt;
    </script>

</body>
</html>


It's erroring on inner = document.getElementById("inner"); - if you change this to var inner = document.getElementById("inner"); it will work.

IE is automatically creating a global inner variable due to the id on the element - it really doesn't seem to like you trying to assign things to it.


Hit F12 to get the script debugger and review the script errors. For instance, rather than trying to assign what you hoped is a new variable named "inner" (which actually maps to the document's element with ID "inner") you might consider using a variable you've actually declared?

After you fix those, perhaps you want to delay your script until OnLoad fires?


First your html is not complete. The page has no header (<head>).

Second, program precise, using comma's and semicolons everywhere you can. There was no punctuation after the variable declaration in your code. Things like that can break the script. In this case there is a conflict between window[inner] (an internal variable created by the browser) and your 'inner' variable. The lack of a comma/extra var declaration line confused the javascript interpreter, that tried to insert semicolons whilst interpreting. This 'semicolon insertion' is seen as one of the major flaws of javascript (see links @bottom), but can be circumvented with programmers discipline to always do his own semicolon insertion.

With a little more precision your script looks like:

var txt = "Just a quick test!", //use a comma here
           inner = document.getElementById("inner"); 
           //use a semicolon to end var declaration block
inner.innerHTML = txt; //always end statements with semicolon

or

var txt = "Just a quick test!";
var inner = document.getElementById("inner");

That will work in IE.

For further reading
For further reading (2)


IE bombs out when trying to add HTML code into a P tag with innerHTML. Replace your P tags with DIVs to solve the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜