iframe 子父頁面相互調用元素以及方法

iframe 子父頁面相互調用元素以及方法javascript

父頁面html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="assets/js/jquery-2.1.4.min.js"></script>
		<script type="text/javascript">
			function parentfunc(){
				console.log("hello,i'm parent page");
			}
			function childCall(){
				//調用子頁面方法
				window.iframe.childFunc();
				var txt=$("#txtP").val();	
				//訪問子頁面元素
				$("#iframe").contents().find("#txtC").val(txt);  	
			}
		</script>
	</head>
	<body>
		<div>
			<h4>parent page</h4>
			<div>
				<label>父頁面參數:</label>
				<input type="text" id="txtP" value="" />	
			</div>
			<button type="button" id="btnOk" onclick="childCall();" >調用子頁面方法</button>
		</div>
		<div>
			<iframe id="iframe" name="iframe" src="child.html"></iframe>
		</div>
	</body>
</html>

子頁面java

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="assets/js/jquery-2.1.4.min.js"></script>
		<script type="text/javascript">
			function parentCall(){
				//調用父頁面方法
				parent.parentfunc();
				var txt=$("#txtC").val();
				//訪問父頁面元素
				$(window.parent.document).find("#txtP").val(txt);
			}
			
			function childFunc(){
				console.log("hello,i'm child page");
			}
		</script>
	</head>
	<body>
		<div>
			<h4> this is child page</h4>
			<div>
				<label>子頁面參數:</label>
				<input type="text" id="txtC" value="" />	
			</div>
			<button  onclick="parentCall();">調用父頁面方法</button>
		</div>
	</body>
</html>
相關文章
相關標籤/搜索