[英]JavaScript Code is not working in IE8
下面的代码在IE8中不起作用,但是,它在FireFox和Google Chorome上运行良好。即使IE8不会引发任何错误,但输出不会出现。 任何想法? 实际问题是什么?
<html>
<head/>
<body>
<script type="text/javascript">
(function(){
var inpEle = document.createElement("div");
inpEle.setAttribute("id", "div1");
var texEle = document.createTextNode("This is my Sample Para. I am testing it again my own level that prove How i am capable of.");
inpEle.appendChild(texEle);
document.body.appendChild(inpEle);
})();
(function(){
var inpEle1 = document.createElement("input");
inpEle1.setAttribute("type", "button");inpEle1.setAttribute("value", "Show");inpEle1.setAttribute("onclick", "Show()");
document.body.appendChild(inpEle1);
var inpEle2 = document.createElement("input");
inpEle2.setAttribute("type", "button");inpEle2.setAttribute("value", "Hide");inpEle2.setAttribute("onclick", "Hide()");
document.body.appendChild(inpEle2);
})();
</script>
<script type="text/javascript">
window.onload= function(){
document.getElementById('div1').style.display="none";
}
Show = function (){
document.getElementById('div1').style.border="2pt solid green";
document.getElementById('div1').style.display="";
}
Hide = function(){
document.getElementById('div1').style.border="";
document.getElementById('div1').style.display="none";
}
</script>
</body>
</html>
在</body>
标记已被解析并且您的代码试图在仍在解析的过程中追加到正文之前,您可能无法在IE8中使用document.body.appendChild()
。 当您执行此操作时,像IE6这样的IE早期版本可能会中止(例如崩溃)。 更高版本(例如IE8)只会忽略您的请求。
您可以在解析正文时使用document.write()
添加内容。
您可以推迟对代码的调用,直到正文完成加载和解析(例如<body onload="xxx()">
处理程序)之后,或者在诸如window.onload
的事件触发时为止。
您可以将appendChild()
到已完成解析的元素(脚本之前的内容)。
最简单的解决方案可能是在脚本之前的主体中放置<div id="container"></div>
,然后将其附加到主体而不是主体,或者将代码放入函数中,并让body onload事件调用您的函数。
请参阅本文以获取有关问题的描述。
转到Internet选项-安全选项卡-Internet-单击“自定义”按钮,然后向下滚动到“其他”部分。“允许脚本启动的窗口不受大小或位置的限制”找到“活动脚本”,然后选中启用。
不要使用setattribute对事件使用匿名函数
inpEle1.onclick = function() {
Show();
};
它也可以在IE8的IE测试器中使用,但不能在IE7中使用,是否使用IE7兼容性
我注意到,element.style.display并不总是与IE8兼容。
这是一种改善兼容性的方法:
if (element.style.setAttribute)
element.style.setAttribute("display", value);
else
element.style.display = value;
最好的祝福,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.