2010-06-05 139 views
2

我想將iframe元素添加到頁面中,然後在該iframe內添加<p>元素。
我嘗試這樣做:動態添加iframe和段落元素

var iframe = document.createElement('iframe'); 
iframe.frameBorder = 1; 
iframe.width = "500px"; 
iframe.height = "250px"; 
iframe.id = "iframe"; 

var p = document.createElement('p'); 
iframe.appendChild(p); 
document.getElementById("div").appendChild(iframe); //this is a div that I have in body. 

iframe的被添加到頁面,但P不加入的iframe(iframe的身體)

+0

div是div元素的正確ID屬性嗎? – karim79 2010-06-05 22:53:48

+0

當然,iframe添加了但P不是 – shivesh 2010-06-05 22:56:23

回答

5

在現代瀏覽器中,您使用contentDocument屬性。在其他情況下,您必須使用contentWindow.document。您可以在onload事件中使用iframe的文檔創建段落。所以:

var iframe = document.createElement('iframe'); 
iframe.frameBorder = 1; 
iframe.width = "500px"; 
iframe.height = "250px"; 
iframe.id = "iframe"; 

iframe.onload = function() 
{ 
    var doc = iframe.contentDocument || iframe.contentWindow.document; 
    var p = doc.createElement('p'); 
    p.textContent = "Paragraph in iframe"; 
    doc.body.appendChild(p); 
}; 

document.getElementById("div").appendChild(iframe); //this is a div that I have in body. 

我做了一個jsfiddle demo

此外,我建議您不要使用與標記名稱相同的ID。它可能會令人困惑。

+0

非常感謝!我一直試圖在沒有使用onload函數的情況下工作數小時 - 它只是不起作用。嘗試過你的解決方案,並立即開展工作! – ChristophK 2013-07-26 12:34:12

1

希望這將讓你在正確的方向前進:

var p = document.createElement('p'); 

var iFrmDocument = (iframe.contentWindow || iframe.contentDocument); 
if (iFrmDocument.document) iFrmDocument=iFrmDocument.document; 
iFrmDocument.appendChild(p); 

document.getElementById("div").appendChild(iframe); 

這是否有意義?處理[i]幀時有點必要繞道