jQuery子iframe调用父iframe

问题描述

子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>

在这里插入图片描述

发布了223 篇原创文章 · 获赞 63 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/104018803