调用iframe 中的js[兼容各种浏览器]

时间:2022-05-12 13:44:31

*chrome浏览器需要在服务器环境中测试

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<div id="d1"></div>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"> </script>
<script>
$(function() {
var iframe = '<iframe id="f1" src="frame.html"></iframe>';
$("#d1").html(iframe);
onIframeLoaded(f1,function() {
executeIframeFun("a");
}); /**
* iframe加载成功事件
**/
function onIframeLoaded(iframe,onload) {
if (iframe.attachEvent) {
iframe.attachEvent("onload", function() {
onload();
});
} else {
iframe.onload = function() {
onload();
};
}
}
/**
* 执行iframe的方法
* funName 方法名
*/
function executeIframeFun(funName) {
if (window.frames['f1'].contentWindow) {
window.frames['f1'].contentWindow[funName]();
} else {
window.frames['f1'][funName]();
}
} });
</script>
</body>
</html>

iframe html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
子页面
<script type="text/javascript">
function a(){
alert('子页面');
}
</script>
</body>
</html>