web兩個iframe之間互相調用方法

原文鏈接:https://blog.csdn.net/u011785106/article/details/52095804

假如有兩個iframe在同一個頁面上,一個id爲if1,另一個爲if2。
想要在if1中調用if2中的方法,只需在if1中添加如下代碼:

window.parent.document.getElementById('if2').contentWindow.需要調用的方法;
例:
1、main.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
<link href="../css/main.css" rel="stylesheet" type="text/css">


</head>

<body>
    <div>
        <iframe src="if1.html" id="if1"></iframe>
        <iframe src="if2.html" id="if2"></iframe>
    </div>
</body>
</html>

2、if1.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>

<body>
    <button οnclick="window.parent.document.getElementById('if2').contentWindow.show();">測試</button>
</body>
</html>

3、if2.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>if2</title>
<script type="text/javascript">
    function show(){
        alert();
    }

</script>
</head>
<body>


</body>
</html>

運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章