在没有jQuery的情况下从iFrame内部将HTML附加到父级 [英] Appending HTML to parent from inside iFrame without jQuery

查看:43
本文介绍了在没有jQuery的情况下从iFrame内部将HTML附加到父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing in an application where new code is introduced via iframes only. I'm trying to create a function (running inside an iFrame) that will append some html after the iFrame in which it is running. I'd rather not introduce jQuery to resolve this issue. Here is a sample

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

我没有收到任何例外,但是我也从未看到任何结果.

I don't receive any exceptions, but I never see any results either.

将此页面称为InnerPage.html

Call this page 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

Call this page 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>

推荐答案

这有效:

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

这篇关于在没有jQuery的情况下从iFrame内部将HTML附加到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆