问题描述
子iframe使用jQuery访问父页面元素
解决方案
在$()
选择元素时加入第二个参数parent.document
$("", parent.document).val())
实例
index.html
<head>
</head>
<body>
<div style="background-color:orange; height:200px; width:50%; float:left;">
<input id="name" type="text" placeholder="输入姓名">
</div>
<div style="background-color:pink; height:200px; width:50%; float:right;">
<iframe src="iframe.html"></iframe>
</div>
</body>
</html>
iframe.html
<head>
</head>
<body>
<button id="get">获取姓名</button>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
// 子iframe访问父页面元素
$("#get").click(function () {
alert($("#name", parent.document).val());
});
// 子iframe监听父页面元素
$("#name", parent.document).change(function () {
console.log($(this).val());
});
</script>
</body>
</html>