iframe嵌入的页面实现父子元素互相访问

最近在开发中遇到了需在父级页面中调入iframe页,在父页面中给子页面的元素绑定事件,问题来了:怎么获取子页面元素javascript

在iframe页面中获取父页面元素


原文连接:blog.csdn.net/wxl1555/art…css

  • jq方法:$("#id",window.parent.document)
  • js方法:window.parent.document.getElementById("id")
  • 若出现iframe嵌套两层的状况:window.parent.parent.document.getElementById("id"); //以此类推
  • 若嵌套好多层,可直接使用查找顶层元素的方法:window.top.document.getElementById("id");

在iframe中调用父页面元素的方法和变量


原文连接:blog.csdn.net/wxl1555/art…html

  • 使用父页面的方法:parent.methodjava

  • 使用父页面的变量:parent.variablebash

  • 案例ui


<!-- 父页面 iframeParent.html-->
<body>
	<div id="parentBox">我是父页面</div>
	<iframe src="iframeChildren.html" width="300px" height="200px"></iframe>
</body>

<script type="text/javascript">
	var _parent = 'hello';
	var _parent1 = 'world';

	function methodParent(){
		console.log( _parent);
	}
</script>
复制代码

<!--  内嵌的iframe页面 iframeChildren.html-->
<body>
	<div id="childrenBox">我是子页面</div>
</body>

<script type="text/javascript">
	//jQuery操做父页面的元素
	$("#parentBox", parent.document).css('color', 'red');

	//原生的方法操做父页面元素
	var parentRed = window.parent.document.getElementById("parentBox").style.backgroundColor = 'blue';

	//调用父页面的方法
	parent.methodParent();

	//使用父页面的变量
	var _children = parent._parent1;

	console.log(_children);     
</script>
复制代码

在父页面中获取子页面的元素


  • jq方法:$('#id').contents().find('childid')
  • js方法:$('#id')[0].contentWindow.document.getElementById('childid')

在父页面中获取并调用子页面的方法


  • jq方法: iframe.contentWindow.houseInfo();//houseInfo是子页面的js方法

注意

在加载iframe嵌入的子页面时,须要等子页面文档加载完成之后执行代码,因此须要监听iframe的load事件:spa

//jq方法
$('#id').load(function () {
	//子页面须要加载的数据代码
}

//js 方法
document.getElementById('id').onload=function(){
  //子页面须要加载的数据代码
} 
复制代码
相关文章
相关标签/搜索