簡體   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