javascript父、子页面交互技巧总结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript父、子页面交互技巧总结

  2020-05-13 我要评论

帧用来存放子页面,既可以是iframe,又可以是frameset。window对象是全局对象,页面上的一切函数和对象都在它的作用域里。
1、parent代表父窗口、如果父窗口又存在若干层嵌套,则top代表顶级父窗口。
self代表窗口自身。

if(self==top){//}判断窗口是否处于顶级 
if(self==parent){}//也可以

2.1、父页面访问子页面元素。思路是子页面的元素都在其window.document对象里面,先获取它然后就好说了。
帧最好设置name属性,这样操作最方便。如

<iframe name="test" src="child.html"></iframe>

假如要获取child.html里面id为'menu'的元素,则可以这样写:

window.frames["test"].document.getElementById('menu'); 
//由于所有的函数都存放在window对象里面,可去掉开头的window: 
frames["test"].document.getElementById('menu'); 
//在浏览器中,帧的name属性被默认等同于子页面的window对象,因此可以进一步简写: 
test.document.getElementById('menu');

2.2 父页面访问子页面函数或对象。子页面的函数和对象都在其window对象里,同上,关键是获取该对象。

//假如child.html定义了showMesg函数,需要在父中调用,则这样写 
window.frames['test'].showMesg(); 
//简写形式 
test.showMesg(); 
//同理,对象也是如此访问 
alert(test.person);

2.3 其他获取document的方式。
先使用'document.getElementById()'或'document.getElementsByTagName()'把帧作为document下的Element获取,然后访问其属性contentDocument/contentWindow (iframe、frame特有),其中第一个ie7-不支持,第二个chrome不支持.

<iframe id="testId" src="child.html"></iframe> 
//====== 
var doc=document.getElementById('testId'); 
//或者 
var doc=document.getElementsByTagName('iframe')[0]; 
然后 
var winOrdoc=doc.contentDocument||doc.contentWindow;//二选一 
if(winOrdoc.document)winOrdoc=winOrdoc.document; 
winOrdoc.getElementById('menu'); 
//如果需要window对象,则这样写: 
if(winOrdoc.defaultView)winOrdoc=winOrdoc.defaultView;

3.1子页面访问父页面元素。思路同2.1,先获取父窗口window.document对象

parent.window.document.getElementById('parentMenu'); 
//简写 
parent.document.getElementById('parentMenu');

3.2,子页面访问父页面函数或对象。思路同2.2,先获取父窗口window对象。

parent.parentFunction();

最后提一下js的同源策略,即位于A网站的js代码不允许访问位于B网站的内容,即使该代码来源于B网站。假如帧是其它网站的页面,那么按上述方法互相访问时,浏览器应该会提示:'没有权限'错误。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们