a页面通过框架嵌套了b页面,在a页面中有一个下拉列表,选择这个下拉列表,会及时将值传给b页面,并在b页面中通过接收到的值做任何操作,比如查询数据库等。这就用到了js的监听事件,代码如下:
主页代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
主页
<iframe src="a.html" frameborder="0"></iframe>
</body>
</html>
a页面代码:
<html lang="en">
<head>
<title>Document</title>
</head>
<script type="text/javascript">
window.onload = function() {
document.getElementById("parentSelect").onclick = function() {
var val = this.options[this.selectedIndex].value;
document.getElementById("childIframe").contentWindow.postMessage({
value: val
},"*");
};
}
</script>
<body>
a页面
<select name="parentIframe" id="parentSelect">
<option value="1">aaa</option>
<option value="2">bbb</option>
</select>
<iframe src="b.html" frameborder="0" id="childIframe"></iframe>
</body>
</html>
b页面代码:
<html lang="en">
<head>
<title>Document</title>
</head>
<script type="text/javascript">
window.onload = function() {
//子页面监听:
window.addEventListener("message", function(event) {
var data = event.data;
//以下内容为处理业务和调用当前页面的函数方法
if(data.value && data.value ==1){
document.getElementsByClassName("showOption")[0].innerHTML = `
<select name="" id="">
<option value="">请选择</option>
<option value="1">aaaa</option>
<option value="2">bbbbbbb</option>
</select>`
} else {
document.getElementsByClassName("showOption")[0].innerHTML = `
<select name="" id="">
<option value="">请选择</option>
<option value="3">111111111</option>
<option value="4">22222222</option>
</select>`
}
});
}
</script>
<body>
b页面
<div class="showOption">
</div>
</body>
</html>