2012-08-28 39 views
6

我想在下面的代碼中訪問iframe的contentDocument和contentWindow。但他們都是空的。iframe contentDocument和contentWindow爲空

var iframe = document.createElement('iframe'); 
    this.get__domElement$i().appendChild(iframe); 
    if (iframe.contentDocument) { 
     iframe.contentDocument.write("Hello"); 
    } 
    else if (iframe.contentWindow) { 
     iframe.contentWindow.document.body.innerHTML = "Hello"; 
    } 

有人能告訴我這有什麼不對嗎?謝謝

當我做Document.Body.AppendChild(iframe),那麼contentDocument和contentWindow是非空的。

有人可以告訴我什麼是錯誤的時候我附加iframe的div?

非常感謝。

回答

2

我知道這是有點晚了,但我是研究這一點,並無意中發現了你的問題:

我得到了同樣的錯誤,你,因爲在div我試圖追加iframe來不加載,但當我試圖追加iframe。如果DIV加載你的代碼工作:

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
    <body> 
     <div id='test' > 

     </div> 
     <script> 
      var iframe = document.createElement('iframe'); 
      var myDiv = document.getElementById('test'); 
      myDiv.appendChild(iframe); 
      if (iframe.contentDocument) { 
       iframe.contentDocument.write("Hello"); 
      } 
      else if (iframe.contentWindow) { 
       iframe.contentWindow.document.body.innerHTML = "Hello"; 
      } 
     </script> 
    </body> 
</html> 

這裏是一個jsFiddle這個工作代碼和another用在給了一個錯誤TypeError: Cannot call method 'appendChild' of null標籤。

相關問題