當頁面中有iframe時,想在主頁面調用iframe中的方法,可以用contentWindow屬性。但具體用時還有一點要注意,就是必須等頁面加載完成才可以,否則會報錯找不到函數。
例:
父頁面:
<iframe id="son" src="a.html"></iframe>
子頁面:
<body> 這是子頁面 <script> function test() { console.log("子頁面的方法"); } </script> </body>
如果直接這樣寫:
document.getElementById('son').contentWindow.test();
修改:
window.onload=function(){ document.getElementById('son').contentWindow.test(); }
或者:
var map_iframe = document.getElementById("son"); map_iframe.onload = function() { map_iframe.contentWindow.test(); };
這樣就可以了: