繁体   English   中英

动态添加iframe和段落元素

[英]Adding iframe and paragraph elements dynamically

我想将iframe元素添加到页面,然后在该iframe中添加<p>元素。
我尝试了这个:

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的主体)

在现代浏览器中,您使用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演示

另外,我建议您不要使用与标签名称相同的ID。 这可能会造成混乱。

希望这将使您朝正确的方向前进:

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] Frames时有必要绕道而行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM