getElementById.contentDocument错误在IE
-
16-09-2019 - |
题
<html>
<script type="text/javascript">
function func() {
alert(document.getElementById('iView').contentDocument);
}
</script>
<body>
<iframe id="iView" style="width:200px;height:200px;"></iframe>
<a href="#" onclick="func();">click</a>
</body>
</html>
点击后,火狐返回[对象HTMLDocument的]。 Internet浏览器返回未定义。
我如何选择与Internet Explorer的iView元素?感谢。
解决方案
从此页面:
Mozilla的支持访问通过IFrameElm.contentDocument iframe的文档对象的W3C标准,而Internet Explorer要求您通过document.frames [“名称”]来访问它,然后访问所得到的文件。
所以,你需要检测浏览器和IE浏览器做这样的事情,而不是:
document.frames['iView'].document;
其他提示
在跨浏览器相当于contentDocument
(包括Firefox本身,其中contentDocument
确实工作)是contentWindow.document
。
因此,尝试:
alert(document.getElementById('iView').contentWindow.document);
contentWindow
让你的iframe的window
对象的引用,当然.document
只是用于iframe中DOM文档对象。
下面是概括更好的制品。
您似乎想要得到的IFRAME权的内容是什么?
IE7和FF2:
var iframe = document.getElementById('iView');
alert(iframe.contentWindow.document.body.innerHTML);
使用特征检测,如contentDocument
在IE 8的支持:
var iframe = document.getElementById("iView");
var iframeDocument = null;
if (iframe.contentDocument) {
iframeDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
// for IE 5.5, 6 and 7:
iframeDocument = iframe.contentWindow.document;
}
if (!!iframeDocument) {
// do things with the iframe's document object
} else {
// this browser doesn't seem to support the iframe document object
}
contentWindow.document.body.innerHTML
为我工作在Internet Explorer和Firefox,而
contentDocument.body.innerHTML
将仅工作在Firefox。
做这样的事情:
var myFrame = document.getElementById('iView');
var frameDoc = myFrame.contentDocument || myFrame.contentWindow;
if (frameDoc.document){
frameDoc = frameDoc.document;
}
alert(frameDoc);
请参阅此页面更多细节
不隶属于 StackOverflow