Errore di getElementById.contentDocument in IE
-
16-09-2019 - |
Domanda
<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>
Dopo aver fatto clic, Firefox torna [HTMLDocument oggetto]. Internet Explorer restituisce il valore undefined.
Come posso selezionare l'elemento iView con Internet Explorer? Grazie.
Soluzione
Mozilla supporta lo standard W3C di accesso ai documenti oggetto di iframe attraverso IFrameElm.contentDocument, mentre Internet Explorer richiede di accedervi attraverso document.frames [ "nome"] e quindi accedere al documento risultante.
Quindi è necessario rilevare il browser e su IE fare qualcosa del genere, invece:
document.frames['iView'].document;
Altri suggerimenti
L'equivalente cross-browser per contentDocument
(compresi Firefox stesso, dove contentDocument
non di lavoro) è contentWindow.document
.
In modo da provare:
alert(document.getElementById('iView').contentWindow.document);
contentWindow
si ottiene un riferimento all'oggetto window
del iframe, e, naturalmente, .document
è solo l'oggetto DOM dei documenti per l'iframe.
Ti sembra di voler ottenere il contenuto del diritto iframe?
IE7 e FF2:
var iframe = document.getElementById('iView');
alert(iframe.contentWindow.document.body.innerHTML);
rilevazione Usa funzione, come contentDocument
è supportato in 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
sta lavorando per me in Internet Explorer e Firefox, mentre
contentDocument.body.innerHTML
funziona solo in Firefox.
fare qualcosa di simile:
var myFrame = document.getElementById('iView');
var frameDoc = myFrame.contentDocument || myFrame.contentWindow;
if (frameDoc.document){
frameDoc = frameDoc.document;
}
alert(frameDoc);
questa pagina per maggiori dettagli