简体   繁体   English

动态添加iframe和段落元素

[英]Adding iframe and paragraph elements dynamically

I want to add iframe element to the page and then add <p> element inside that iframe. 我想将iframe元素添加到页面,然后在该iframe中添加<p>元素。
I tried this: 我尝试了这个:

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.

The iframe is added to the page but P is not added into iframe(iframe's body) iframe已添加到页面,但P未添加至iframe(iframe的主体)

In modern browsers, you use the contentDocument attribute. 在现代浏览器中,您使用contentDocument属性。 In others, you have to use contentWindow.document. 在其他情况下,您必须使用contentWindow.document。 You create the paragraph using the iframe's document, in the onload event. 您可以在onload事件中使用iframe文档创建段落。 So: 所以:

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.

I made a jsfiddle demo . 我做了一个jsfiddle演示

Also, I recommend you don't use ids that are the same as the tag name. 另外,我建议您不要使用与标签名称相同的ID。 It could become confusing. 这可能会造成混乱。

hopefully this will get you going in the right direction: 希望这将使您朝正确的方向前进:

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);

Does that make sense? 那有意义吗? It's a bit of a necessary detour when dealing with [i]Frames 处理[i] Frames时有必要绕道而行

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

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