因為iframe頁面於包括父頁面在內的其他頁面通訊有跨域問題,所以只有在服務器環境下或者火狐瀏覽器下才能測試。
在iframe頁面調用父頁面的函數采用parent,例子:在父頁面有一個say()函數,在iframe頁面可以這樣調用parent.say();
如果在頁面內有多個iframe,可以用parent[0],parent[1]...這樣定位到某個iframe。
1、在index.html頁面下有iframe1.html 和 iframe2.html。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<iframe name="iframe1" src="iframe1.html" id="if1" frameborder="0" width="500" height="500"></iframe>
<iframe name="iframe2" src="iframe2.html" id="if2"></iframe>
</body>
</html>
2、iframe1.html里有自定義兩個函數say()和callChild();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe1</title>
<script type="text/javascript">
function say() {
alert("來着iframe1頁面");
}
function callChild()
{
parent[1].window.say();
}
</script>
</head>
<body>
<input type=button value="調用iframe2中的函數say()" onclick="callChild()">
</body>
</html>
3、2、iframe2.html里有自定義兩個函數say()和callChild();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe2</title>
<script type="text/javascript">
function say()
{
alert("來自iframe2頁面");
}
function callParent() {
parent[0].say();
}
</script>
</head>
<body>
<input type=button value="調用iframe1中的say()函數" onclick="callParent()">
</body>
</html>