javascript - iframe移除时,挂在父window下的方法无法调用
怪我咯
怪我咯 2017-04-10 15:25:02
0
0
725

我在index页面嵌套一个iframe,引入iframe.html,iframe上有一个方法,叫‘say’,在iframe页面将其赋给父window。(两个页面同域)
Q:

  1. 当iframe存在时,挂在父window下的方法能成功调用,当移除iframe时,方法无法调用,但是在控制台能console出该方法的信息
  2. window.parent.say 存的是子页面say方法的引用,window.parent.obj存的也是引用,当iframe删除时,obj的值存在父window上,而say方法却无法调用,这是为什么?

以下是两个页面的源码:

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<iframe src="./iframe.html" frameborder="0"></iframe>
<button onclick="deleteDOM()">delete</button>
<button onclick="say()">say</button>
<button onclick="rebornIframe()">rebornMap</button>
</body>
<script>
    function deleteDOM() {
        document.body.removeChild(document.getElementsByTagName('iframe')[0]);
    }
    function say(){
        if (window.sayHello) {
            sayHello()
        }
    }
    function rebornIframe(){
        var createNode = document.createElement('iframe');
        var createAttr  = document.createAttribute('src');
        createAttr.value = "iframe.html";
        createNode.setAttributeNode(createAttr);
        document.body.appendChild(createNode);
    }
</script>
</html>

iframe.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
        <title></title>
    </head>
    <body>
    <p>this is a iframe</p>
    </body>
    </html>
    <script type="text/javascript">
        var sayHello = function(){
            console.info('hello')
        };

        window.parent.sayHello = sayHello;

        var obj = {
            a:1
        };

        window.parent.obj = obj;

        var Person = function(name){
            this.name = name;
        };

        var student = new Person('xiaoming');

        window.parent.student = student;

    </script>

怪我咯
怪我咯

走同样的路,发现不同的人生

membalas semua(0)
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan