动态添加iframe和段落元素 [英] Adding iframe and paragraph elements dynamically

查看:759
本文介绍了动态添加iframe和段落元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将iframe元素添加到页面,然后在iframe中添加< p> 元素。

我试过这个: 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); //这是我在体内的一个div。

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 =iframe中的段落;
doc.body.appendChild(p);
};

document.getElementById(div)。appendChild(iframe); //这是我在体内的一个div。

我做了一个 jsfiddle demo

另外,我建议你不要使用与标签名称相同的id。这可能会令人困惑。


I want to add iframe element to the page and then add <p> element inside that iframe.
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)

解决方案

In modern browsers, you use the contentDocument attribute. In others, you have to use contentWindow.document. You create the paragraph using the iframe's document, in the onload event. 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.

Also, I recommend you don't use ids that are the same as the tag name. It could become confusing.

这篇关于动态添加iframe和段落元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆