向iframe添加元素

时间:2012-12-04 16:44:24

标签: javascript html iframe

我正在创建一个包含iframe的页面。我的目标是创建一个javascript,它将添加到iframe内容的头部。

但我总是得到错误暗示iframe.contentDocument为空。

主页代码

<html>
<head>
<title>Sample "Hello, World" Application</title>
<script type="text/javascript" >
function sizeFrame() {
try{
    var ifrm = document.getElementById("CFrame");
    var bt = ifrm.contentDocument.createElement("base");
    bt.setAttribute("target", "_parent");
    ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);
}
catch (er)
{alert(er);}
}
</script>
</head>
<body>
<div id="sidecontainer">
<iframe id="SFrame" name="SearchFrame" frameborder ="0" width="500" height="100" scrolling="no" src="SearchBox.html"></iframe>
</div>
<div id="content">
<iframe id="CFrame" name="ContentFrame" frameborder="0" height="1000px" width="1000px" onload="sizeFrame()" scrolling="no" src="ContentFrame.html"></iframe>
</div>
</body>
</html>

Iframe ContentFrame.html的代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
    <div id="input">
    test
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

我建议你试试

ifrm.contentWindow.document.getElementById("id")

答案 1 :(得分:0)

使用框架窗口名称来创建元素,就像在主窗口中一样,如下所示

ContentFrame.document...

换句话说,访问窗口名称。

此外,您的iframe窗口没有任何id值等于“id”的元素。

相关问题