设置动态创建的 iframe 的基本标签

aqu*_*ket 5 javascript tags iframe dynamic radix

我正在尝试动态创建 iframe 并在创建之前设置它的基本标记。

ifrm = document.createElement("IFRAME"); 
ifrm.setAttribute("src", "test.html"); 
ifrm.style.width = 400+"px"; 
ifrm.style.height = 100+"px"; 

//before creating it, can we set he base tag?
//I.E. <base href="http://example.com/MyFolder/" />
var bt = ifrm.contentDocument.createElement("base");
bt.setAttribute("href", "http://www.example.com/Folder/");
ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);

document.body.appendChild(ifrm);
Run Code Online (Sandbox Code Playgroud)

我知道我可以在 iframes src 文件本身中设置基本标签。但我需要在这里设置它。谢谢。

SLa*_*aks 4

您可以将一个<base>元素附加到ifrm.contentDocument.getElementsByTagName("head").

您需要通过调用在子文档中创建它ifrm.contentDocument.createElement("base")

例如:

var bt = ifrm.contentDocument.createElement("base");
bt.setAttribute(...);
ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);
Run Code Online (Sandbox Code Playgroud)