欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript父、子頁面交互技巧總結(jié)

 更新時間:2014年08月08日 14:46:08   投稿:whsnow  
存放子頁面可以是iframe,又可以是frameset,本例介紹javascript父、子頁面交互技巧,需要的朋友可以參考下

幀用來存放子頁面,既可以是iframe,又可以是frameset。window對象是全局對象,頁面上的一切函數(shù)和對象都在它的作用域里。
1、parent代表父窗口、如果父窗口又存在若干層嵌套,則top代表頂級父窗口。
self代表窗口自身。

if(self==top){//}判斷窗口是否處于頂級 
if(self==parent){}//也可以

2.1、父頁面訪問子頁面元素。思路是子頁面的元素都在其window.document對象里面,先獲取它然后就好說了。
幀最好設(shè)置name屬性,這樣操作最方便。如

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

假如要獲取child.html里面id為'menu'的元素,則可以這樣寫:

window.frames["test"].document.getElementById('menu'); 
//由于所有的函數(shù)都存放在window對象里面,可去掉開頭的window: 
frames["test"].document.getElementById('menu'); 
//在瀏覽器中,幀的name屬性被默認(rèn)等同于子頁面的window對象,因此可以進一步簡寫: 
test.document.getElementById('menu');

2.2 父頁面訪問子頁面函數(shù)或?qū)ο蟆W禹撁娴暮瘮?shù)和對象都在其window對象里,同上,關(guān)鍵是獲取該對象。

//假如child.html定義了showMesg函數(shù),需要在父中調(diào)用,則這樣寫 
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,子頁面訪問父頁面函數(shù)或?qū)ο蟆K悸吠?.2,先獲取父窗口window對象。

parent.parentFunction();

最后提一下js的同源策略,即位于A網(wǎng)站的js代碼不允許訪問位于B網(wǎng)站的內(nèi)容,即使該代碼來源于B網(wǎng)站。假如幀是其它網(wǎng)站的頁面,那么按上述方法互相訪問時,瀏覽器應(yīng)該會提示:'沒有權(quán)限'錯誤。

相關(guān)文章

最新評論