引言:
程序員最痛苦的事情就是, 面試問題都是最流行的知識及框架, 進去一看各種老舊框架和知識. 代碼和邏輯揉雜混亂. 兼之無人指導抑或交接人員知而不言言而不盡. 到自己開發的時候, 到處百度,
怎么一個難字了得.
今天要講的就是js之iframe 父子傳值及函數調用.
說到iframe, 我老婆都嘲笑, 說太low了, 現在正是vue當道. 鬼還用iframe嵌套.
可是我現在的項目就是用的iframe, 也不分什么前后端, 就是一個人搞定. 領導只關心功能能不能實現. 不管你用的方法! 項目中我最大的困惑就是
js調用函數的時候, 一會兒加parent,一會兒不加.看js都放在同一個目錄下了. 百度了很多還是有些懵懂.
今天我大致明白了, 故寫下這篇博客. 以饗讀者及自己.
一: 目錄結構
1.1 非跨域
a.html 父頁面包含一個iframe
1 <html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 4 <title>A</title> 5 <script type="text/javascript" src="js/a.js"></script> 6 </head> 7 <body> 8 父級:A頁面<br/> 9 <textarea id="a_text">aaaaa</textarea><br/> 10 <button id="a_button" onclick="receive()" >a頁面button</button><br/><br/> 11 <iframe src="b.html" width="500px" height="200px" id="iframe"></iframe> 12 </body> 13 </html>
b.html 子iframe頁面
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>B</title> <script type="text/javascript" src="js/b.js"></script> </head> <body> 子級:B頁面<br/> <textarea id="b_text">bbbbb</textarea><br/> <button id="b_button" onclick="getFromA()" >B頁面獲取A頁面數據</button><br/> </body> </html>
效果圖:
a.js 父頁面引用的js文件
function helloworld(){ debugger; alert("hello world"); } //helloworld = function(){ // alert(123) //} function receive(){ document.getElementById("a_button").onclick = function(){ alert(document.getElementById("iframe").contentWindow.document.getElementById("b_text").value); } }
b.js 子頁面引用的js文件
function getFromA() { alert(parent.document.getElementById("a_text").value); }
開始試驗:
1). 點擊父頁面的button獲取子頁面的textarea的值
2). 點擊子頁面的button獲取父頁面的textarea值
1.2 跨域
父頁面c.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>c</title> <script type="text/javascript" src="js/c.js"></script> </head> <body> 父級:A頁面<br/><br/> <iframe src="d.html" width="500px" height="200px" id="iframe"></iframe> <div><input type="button" value="調用子級函數" onclick="getFromB()"></div> </body> </html>
子頁面: d.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>d</title> <script type="text/javascript" src="js/d.js"></script> </head> <body> 子級:B頁面<br/> <button id="b_button" onclick="send()">B頁面發送A頁面數據</button><br/> </body> </html>
效果圖:
c.js : 父頁面引用的js文件
window.addEventListener('message', function(e) { debugger; alert(JSON.stringify(e.data)); console.log('獲取子級B頁面返回值:'); console.log(e.data); }) function hellworld(){ alert("c.js hello world!"); } function getFromB(){ document.getElementById("iframe").contentWindow.helloworld(); }
d.js 子頁面引用的js文件
function send(){ debugger; var param = {'name':'admin', 'age': 88}; window.parent.postMessage(param,'*'); window.parent.hellworld(); } function helloworld(){ alert("d.js helloworld"); }
開始測驗:
1. 子頁面發數據父頁面接受數據
2. 父頁面調用子頁面js的函數
總結:
html的js的函數調用, 什么時候用parent及contentWindow,看的不是js所在位置目錄,
而是要看頁面在html中不同位置,來判斷!!!!