从 iFrame 内部将 HTML 附加到父级,而无需 jQuery

Appending HTML to parent from inside iFrame without jQuery

本文关键字:jQuery 内部 iFrame HTML      更新时间:2023-09-26

我正在开发一个应用程序,其中新代码仅通过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);
    }

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

使用完整代码更新

将此页面称为内部页面.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>

将此页面称为外页.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>

这有效:

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';           
}