当页面中有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(); };
这样就可以了: