本文介紹了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>
新聞熱點
疑難解答
圖片精選