`
huanyq2008
  • 浏览: 166862 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

子页面和父页面的相互调用

阅读更多

父页面

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
var parentStr = "-----父页面的js变量-----";
function getValue(){
	document.getElementById("getText").value = document.getElementById("framePage").contentWindow.document.getElementById("forParent").value;
}
function getJsVar(){
	document.getElementById("getText").value = document.getElementById("framePage").contentWindow.childStr;
}
function getFunc(){
	document.getElementById("framePage").contentWindow.testFunc();
}
function testFunc(){
	alert("子页面调用了此方法!");
}
</script>
</head>

<body>
子页面获取<input type="text" id="forChild" value="parent"/><br/>
<input type="text" id="getText"/>
<button onclick="getValue()">获得子页面的值</button><button onclick="getJsVar()">获得子页面的Js变量</button><button onclick="getFunc()">调用子页面的Js方法</button><br/><br/><br/><br/><br/>

<iframe id="framePage" name="framePage" style="width:100%;height:500px" src="childPage.html"/>
</body>
</html>

 

子页面

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
var childStr = "子页面的js变量";
function getValue(){
	document.getElementById("getText").value = parent.document.getElementById("forChild").value;
}
function getParentJsVar(){
	document.getElementById("getText").value = parent.parentStr;
}
function getFunc(){
	parent.testFunc();
}
function testFunc(){
	alert("父页面调用了此方法!");
}
</script>
</head>

<body>
父页面获取<input type="text" id="forParent" value="child"/><br/>
<input type="text" id="getText"/>
<button onclick="getValue()">获得父页面的值</button><button onclick="getParentJsVar()">获得父页面的Js变量</button><button onclick="getFunc()">获得父页面的值</button>
</body>
</html>

 

 

 

经验总结:

1. 子页面调用父页面不会有什么大的问题。但父页面调用子页面时需要确保子页面已经加载完成,不然就会报错。这个无需多说。 有两种解决方式:

   1) 在父页面用setTimeout设置延时调用

   2) 在子页面onload完成后,触发父页面来调用子页面。

2. 注意:在web开发过程中,有时出现问题,需要考虑HTML 文档遵循的文档类型是否有影响。

  如:<!DOCTYPE html 。。。。。。。。

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics