引言:
程序员最痛苦的事情就是, 面试问题都是最流行的知识及框架, 进去一看各种老旧框架和知识. 代码和逻辑揉杂混乱. 兼之无人指导抑或交接人员知而不言言而不尽. 到自己开发的时候, 到处百度,
怎么一个难字了得.
今天要讲的就是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中不同位置,来判断!!!!