1

我正在开发一个仅通过 iframe 引入新代码的应用程序。我正在尝试创建一个函数(在 iFrame 内运行),它将在运行它的 iFrame 之后附加一些 html。我宁愿不引入 jQuery 来解决这个问题。这是一个示例

    function AppendDivAfteriFrame() {
        var iFrame = window.parent.document.getElementById(window.frameElement.id)
        var newDivInParent = window.parent.document.createElement('div');
        newDivInParent.setAttribute("Id", "MyDiv");
        newDivInParent.innerHTML = 'Hello World!  I am outside the iFrame';
        iFrame.appendChild(newDivInParent);
    }

我没有收到任何异常,但我也从未看到任何结果。

更新完整代码

调用这个页面InnerPage.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function AppendDivAfteriFrame() {
            var iFrame = window.parent.document.getElementById(window.frameElement.id)
            var newDivInParent = window.parent.document.createElement('div');
            newDivInParent.setAttribute("Id", "MyDiv");
            iFrame.appendChild(newDivInParent);
            parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
        }
    </script>
</head>
<body>
    <button onclick="AppendDivAfteriFrame()">Append HTML</button>    
</body>
</html>

将此页面称为 OuterPage.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <iframe src="InnerPage.html" id="MyiFrame"></iframe>
</body>    
</html>
4

1 回答 1

2

这有效:

function AppendDivAfteriFrame() {
     var iFrame = window.parent.document.getElementById(window.frameElement.id)
     var newDivInParent = window.parent.document.createElement('div');
     newDivInParent.setAttribute("Id", "MyDiv");
     iFrame.parentNode.appendChild(newDivInParent);  //Edited here
     parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';           
}
于 2013-10-24T03:42:33.373 回答