jQuery call the parent child iframe iframe

Problem Description

Child iframe using jQuery access to the parent page elements

solution

The $()addition of a second element selected parameterparent.document

$("", parent.document).val())

Examples

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>

Here Insert Picture Description

Published 223 original articles · won praise 63 · views 120 000 +

Guess you like

Origin blog.csdn.net/lly1122334/article/details/104018803