iframe 子页面获取父页面数据的方法
首先说一下基本需求:
一个父页面要调用多个 iframe 子页面,点击子页面的按钮,弹出模态框,输入数据点击确定,iframe子页面可以获取到模态框的数据。
由于这里涉及到跨域问题,所以要搭建web服务器(这里不清楚的可以上网搜一下)。下面就直入主题了!主页面 index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>iframe 主页面</title>
<style>
.bg{
background-color:black;
opacity:0.5;
height:100%;
position:absolute;
top:0;
left:0;
display:none;
}
.content{
width:400px;
height:400px;
margin:200px 200px;
background-color:#fff;
padding:10px;
text-align:center;
}
</style>
</head>
<body>
<iframe class="newiframe" id='mainFrame' scrolling="no" src="iframe.html" width='600px' height='600px'></iframe>
<!-- 模态框 -->
<div class="bg" id="modal">
<div class="content">
姓名:<input type="text" value=""><br />
年龄:<input type="text" value=""><br />
<button>提交</button>
</div>
<div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="index.js"></script><script></script>
</html>iframe 子页面
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>index</title>
</head>
<body>
<div>
<p>iframe1</p>
<p>iframe11</p>
<button>click111</button><br/>
</div>
<div>
<p>iframe2</p>
<p>iframe21</p>
<button>click222</button><br/>
</div>
<div>
<p>iframe3</p>
<p>iframe31</p>
<button>click333</button><br/>
</div>
<div>
<p>iframe4</p>
<p>iframe41</p>
<button>click444</button><br/>
</div>
<div>
<p>iframe5</p>
<p>iframe51</p>
<button>click555</button>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="index.js"></script>
</html>公共的js文件 index.js
(function(){window.parent.document
var index = {
fn:function(){
var click = true;
$('.bg .content').click(function(event){
//阻止冒泡
event.stopPropagation();
click = false;
})
$('.bg button').on("click",function(){
//此处hide() 必须加时间
$("#modal").hide(100);
})
if(click){
$('.bg').on("click",function(){
$(this).hide(100)
})
}
},
iframe: function(){
var _this;
$("button").click(function(){
_this = $(this);
//改变主页面模态框的显示隐藏状态
$('.bg',).show();window.parent.document
})
$("button",).click(function(){window.parent.document
var data = {
"name":$("input",).eq(0).val(),window.parent.document
"age":$("input",).eq(1).val()
};
$(_this).siblings('p').eq(0).html(data['name']);
$(_this).siblings('p').eq(1).html(data['age']);
})
}
}
index.fn();
index.iframe();
})()
PS: js文件要放在文档底部
2921

被折叠的 条评论
为什么被折叠?



