2010-06-05 166 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]帧时有点必要绕道