使用iframe父页面调用子页面和子页面调用父页面的元素与方法

时间:2023-03-08 17:13:49

在实际的项目开发中,iframe框架经常使用,主要用于引入其他的页面。下面主要介绍一下使用iframe引入其他页面后,父页面如何调用子页面的方法和元素以及子页面如何调用父页面的方法和元素。

1、父页面获取子页面的元素

//jquery方式

$("#iframeId").contents().find("#child1");

//js方式

window.frames["iframName"].document.getElementById("child1");

2、父页面获取子页面方法

iframName.window.childrenFn();

3、子页面获取父页面元素

//jquery方式

$("#parent1",parent.document);

//js方式

window.parent.document.getElementById("parent1");

4、子页面获取父页面方法

parent.parentFn();

父页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>父页面</title>
</head>
<body>
<iframe src="iframechildren.html" width="100" height="100" name="iframName" id="iframeId"></iframe>
<div id="parent1">调用子页面元素</div>
<div id="parent2">调用子页面方法</div>
<script src="js/jquery-1.9.1.js"></script>
<script>
function parentFn () {
alert("我是父页面的方法");
}
//父页面获取子页面元素
$("#parent1").click(function () {
//jquery方式
$("#iframeId").contents().find("#child1").css("color","#FF0000");
//js方式
window.frames["iframName"].document.getElementById("child1").style.color = "#FF0000";
});
//父页面获取子页面方法
$("#parent2").click(function () {
iframName.window.childrenFn();
});
</script>
</body>
</html>

子页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>子页面</title>
</head>
<body>
<div id="child1">调用父页面元素</div>
<div id="child2">调用父页面方法</div>
<script src="js/jquery-1.9.1.js"></script>
<script>
function childrenFn() {
alert("我是子页面的方法");
}
//调用父页面元素
$("#child1").click(function () {
//jquery方式
$("#parent1",parent.document).css("color","#00f");
//js方式
window.parent.document.getElementById("parent1").style.color = "#00f";
});
//调用父页面方法
$("#child2").click(function () {
parent.parentFn();
});
</script>
</body>
</html>