我在index页面嵌套一个iframe,引入iframe.html,iframe上有一个方法,叫‘say’,在iframe页面将其赋给父window。(两个页面同域)
Q:
- 当iframe存在时,挂在父window下的方法能成功调用,当移除iframe时,方法无法调用,但是在控制台能console出该方法的信息
- 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>
<div>this is a iframe</div>
</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>