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(){
  //子頁面須要加載的數據代碼
} 
複製代碼
相關文章
相關標籤/搜索