最近在开发中遇到了需在父级页面中调入iframe页,在父页面中给子页面的元素绑定事件,问题来了:怎么获取子页面元素
在iframe页面中获取父页面元素
- jq方法:$("#id",window.parent.document)
- js方法:window.parent.document.getElementById("id")
- 若出现iframe嵌套两层的情况:window.parent.parent.document.getElementById("id"); //以此类推
- 若嵌套好多层,可直接使用查找顶层元素的方法:window.top.document.getElementById("id");
在iframe中调用父页面元素的方法和变量
-
使用父页面的方法:parent.method
-
使用父页面的变量:parent.variable
-
案例
<!-- 父页面 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事件:
//jq方法
$('#id').load(function () {
//子页面需要加载的数据代码
}
//js 方法
document.getElementById('id').onload=function(){
//子页面需要加载的数据代码
}