1. 程式人生 > >top.location和location.href的區別

top.location和location.href的區別

一個 type .com src func www set parent ati

轉自:http://www.cnblogs.com/liangyu/articles/2530884.html

top.location.href=”url” 在頂層頁面打開url(跳出框架)

self.location.href=”url” 僅在本頁面打開url地址

parent.location.href=”url”   在父窗口打開Url地址

this.location.href=”url”    用法和self的用法一致

if (top.location == self.location) 判斷當前location 是否為頂層 來禁止frame引用,如果頁面當中有自定義的frame的話,也可以將parent self top換為自定義frame的名稱 ,效果就是在自定義frame窗口打開url。

實際中可能這樣使用:

1 if(top !== self){            
2 
3    top.location.href = location.href;
4 
5 }   //禁止frame引用

以下是從網上找到的一個例子,不是很直觀, 我加了上面那三行代碼, 可以先去掉, 再加上, 看一下效果,就很清楚了。

top.htm 代碼:

 1 <script language=javascript>
 2 
 3    function rs(){
 4 
 5     if(top !== self){
 6 
 7       top.location.href 
= location.href; 8 9     } 10 11     parent.left.location.href="top.htm"12 13     parent.bot.location.href="top.htm"14 15 } 16 17 < /script> 18 19 < input type=button name=name value="ksdj" onclick=rs();>

以下是一個隨意文件名的htm文件:

 1 <FRAMESET COLS="150,*">
 2 
 3     <
FRAME SRC="left.htm" name=left> 4 5     < FRAMESET ROWS="150,*"> 6 7      < FRAME SRC="top.htm" name=top> 8 9      < FRAME SRC="bot.htm" name=bot> 10 11     < /FRAMESET> 12 13 < /FRAMESET>  

試試,可能是這樣的效果!

top表示主窗口,location表示當前窗口,如果你的文件只有一個框架,沒有iframe和frmaeset,那麽是完全一致的,沒有區別。

top.location是在頂層frame中打開新頁 window.location是在當前frame中打開新頁

parent.location 在當前窗口的父窗口打開Url地址

top.location和location.href的區別