繁体   English   中英

如何在不使用write()的情况下将iframe文档替换为另一个现有的文档对象

[英]How to replace iframe document with another pre-existing document object, without using write()

我只想用一个预先存在的文档对象替换一个空白的iframe文档。 不是可以与write()方法一起使用的HTML字符串(该解决方案在许多其他答案中) 我只希望一个文档对象替换另一个文档。


我的空白iframe:

<iframe src="about:blank" id="myIframe"></iframe>


替换空白iframe文档的例程:

function replaceIframeDoc(objDoc){
    var nod_if    = document.getElementById("myIframe");
    var nod_ifDoc = nod_if.contentWindow.document || nod_if.contentDocument;
    nod_ifDoc     = objDoc;
}


创建文档对象,并调用执行替换:
(注意:我将我的文档对象封装在一个简单的对象中……我需要对其他一些不相关的东西进行此处理……只是为了轻松地传递一些属性,等等。希望这对我的问题无关紧要!)

var obj_container = new Object;  //just to make easier to do some other stuff
obj_container.document = document.implementation.createHTMLDocument();
obj_container.document.open();
obj_container.document.write("<html>...(some html)...</html>");
obj_container.document.close();
replaceIframeDoc(obj_container.document);

根据您需要支持的浏览器,您可以执行以下操作:

var iframe = document.getElementById("myIframe");;
var oldNode = iframe.contentDocument.getElementById("myNode");
var newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);

您可以在此处阅读更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/API/document.importNode

暂无
暂无

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

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