首页 > 语言 > JavaScript > 正文

layer弹出子iframe层父子页面传值的实现方法

2024-05-06 15:27:48
字体:
来源:转载
供稿:网友

本文介绍了layer弹出子iframe层父子页面传值的实现方法,分享给大家,具体如下:

父页面获取子页面元素

格式:

$("#iframeID").contents().find("#eleID")

示例代码:

father.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>父级页面</title>  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>  <style>    .btn{display:inline-block;height:30px;line-height:30px;border-radius:5px;background:darkturquoise;padding:5px 12px;color:#fff;cursor:pointer;margin-right:20px;}  </style></head><body><div>  <span id="father_dataChange" class="btn">父向子传值</span></div><iframe id="iframe_dataChange" src="son.html" frameborder="0"></iframe><script>  $("#father_dataChange").click(function () {   $("#iframe_dataChange").contents().find("#son_dataChange").html("我是父页面传过来的值……")  })</script></body></html>

son.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>子级页面</title>  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script></head><body><div id="son_dataChange">我是子页面内容,点击“父向子传值”按钮我改变</div></body></html>

父页面调用子页面方法

格式:

$("#iframeID")[0].contentWindow.fun()

参数:fun()为子页面的函数

注意:$("#iframeID")[0]后面这个[0]必须要,亲测,删除就报错了,其原因是contentWindow是原生js的方法,所以用.eq(0)都不行。

示例代码:

father.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>父级页面</title>  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>  <style>    .btn{display:inline-block;height:30px;line-height:30px;border-radius:5px;background:darkturquoise;padding:5px 12px;color:#fff;cursor:pointer;margin-right:20px;}  </style></head><body><div>  <span id="father_fun" class="btn">父调子函数</span></div><iframe id="iframe_fun" src="son.html" frameborder="0"></iframe><script>  $("#father_fun").click(function () {   $("#iframe_fun")[0].contentWindow.son_fun()  })</script></body></html>

son.html

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>子级页面</title>  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script></head><body><div id="son_fun">我是子页面内容,点击“父调子函数”按钮我改变</div><script>  function son_fun() {   $("#son_fun").html("我变啦!啦啦啦……")  }</script></body></html>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选