您的位置:首页 > 其它

iframe父子页面之间相互调用元素和函数

2015-11-09 14:07 555 查看
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<style>
*{padding:0;margin:0}
#box{width:450px;height:200px;border:2px solid red;margin:30px auto;}
#box iframe{width:100%;height:100%;}
</style>
</head>
<body>

<div id="box">
<iframe src="children.html" id="iframebox" frameborder="0" scrolling="yes"></iframe>
</div>
<div id="pmsg"></div>
<div id="pmsg1"></div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">

/*
iframe中父子页面之间的数据传递
*/
//javascript版本
window.onload = function(){
//父页面调用子页面的元素和事件
//var iframebox = document.getElementById("iframebox");

//var cwinDom = iframebox.contentWindow;//获取的是window,而不是domcument对象
//cwinDom.document.getElementById("regbox").innerHTML = "皮皮,已经登录了。。。";  //需要在服务器中访问,否则会抛跨域异常

//var json = {msg:"皮皮,已经邮寄一份礼物给你了,注意查收"};
//cwinDom.getMsg(json);
}

function msg(msg){
document.getElementById("pmsg1").innerHTML = msg;
}

//jQuery版本
window.onload = function(){
var $frame = $("#iframebox").contents();
$frame.find("#regbox").html("皮皮,已经登录了。。。");

var json = {msg:"皮皮,已经邮寄一份礼物给你了,注意查收"};
$("#iframebox")[0].contentWindow.getMsg(json);
}

</script>

</body>
</html>


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body style="overflow:auto;">
<div id="regbox">登陆、注册</div>

<div id="msg"></div>

<script type="text/javascript">

function getMsg(params){
alert(99);
document.getElementById("msg").innerHTML = params.msg+'<br/>收到了,谢谢';

//调用父页面的元素和事件
parent.document.getElementById("pmsg").innerHTML = "礼物已收到了,谢谢";
parent.msg("调用了下父页面的事件");

//jQuery
$(parent.document).find("pmsg").html("礼物已收到了,谢谢");
}

</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: