window.location.href、location.href是本頁面跳轉 parent.location.href是上一層頁面跳轉 top.location.href是最外層的頁面跳轉 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地址
實際中可能這樣使用
if(top !== self){ top.location.href = location.href; } 禁止frame引用
以下是從網上找到的一個例子,不是很直觀, 我加了上面那三行代碼, 可以先去掉, 再加上, 看一下效果,就很清楚了 以下是top.htm 代碼 <script language=javascript> function rs(){
if(top !== self){ top.location.href = location.href; } parent.left.location.href="top.htm" parent.bot.location.href="top.htm" } < /script> < input type=button name=name value="ksdj" onclick=rs();>
以下是一個隨意文件名的htm文件: <FRAMESET COLS="150,*"> < FRAME SRC="left.htm" name=left> < FRAMESET ROWS="150,*"> < FRAME SRC="top.htm" name=top> < FRAME SRC="bot.htm" name=bot> < /FRAMESET> < /FRAMESET> 你自己試試,我想你要的可能就是這樣的效果!
top表示主窗口,location表示當前窗口,如果你的文件只有一個框架,沒有iframe和frmaeset,那么是完全一致的,沒有區別。
一:提出問題
使用js的同學一定知道js的location.href的作用是什么,但是在js中關於location.href的用法究竟有哪幾種,究竟有哪些區別,估計很多人都不知道了。
blog已經遷移到這里了,有更多文章,歡迎大家訪問。
二:常見的幾種形式
目前在開發中經常要用到的幾種形式有:
self.location.href;
window.location.href;
this.location.href;
location.href;
parent.location.href;
top.location.href;
經常見到的大概有以上幾種形式。
三:代碼部分
那么,這幾種形式的跳轉究竟有什么區別呢?
直接講定義,你肯定不會理解透徹,下面我來貼四個html代碼,用實際的例子講解。
a.html:
<form id="form1" action=""> <div><strong>這是a.html頁面<strong> <iframe src="b.html" width="500px" height="300px"></iframe> </strong></strong></div> </form> <pre>
b.html:
<span>這是b.html</span><span id="span1"></span><br /> <iframe src="c.html" width="500px" height="300px"></iframe>
c.html:
<span><strong>這是c.html:<strong></span><span id="span1"></span><br /> <iframe src="d.html" width="500px" height="300px"></iframe>
d.html:
<span>這是d.html:</span><span id="span1"></span><br /> <input type='button' onclick='jump();' value='跳轉'>
a.html,b.html,c.html,d.html通過iframe給聯系到了一起,那么它們有什么的聯系呢?
觀察代碼,我們可以看出:
a.html里面嵌着b.html;
b.html里面嵌着c.html;
c.html里面嵌着d.html
四:測試幾種用法
下面來測試上述幾種寫法.
在d.html里面head部分寫js:
function jump() { //經測試:window.location.href與location.href,self.location.href,location.href都是本頁面跳轉 //作用一樣 window.location.href="http://www.baidu.com"; //location.href="http://www.baidu.com"; //self.location.href="http://www.baidu.com"; //this.location.href="http://www.baidu.com"; //location.href="http://www.baidu.com"; }
對比圖一和圖二的變化,你會發現d.html部分已經跳轉到了百度的首頁,而其它地方沒有發生變化。這也就解釋了"本頁跳轉"是什么意思。
好,再來修改d.html里面的js部分為:
function jump() { parent.location.href='http://www.baidu.com'; }
運行a.html后,再次點擊"跳轉" 按鈕,運行結果貼圖三如下:
對比圖一和圖三,你會發現a.html中嵌套的c.html部分已經跳轉到了百度首頁。
分析:我點擊的是a.html中嵌套的d.html部分的跳轉按鈕,結果是a.html中嵌套的c.html部分跳轉到了百度首頁,這就解釋了"parent.location.href是上一層頁面跳轉"的意思。
再次修改d.html里面的js部分為:
function jump() { top.location.href='http://www.baidu.com'; }
運行a.html后,再次點擊"跳轉" 按鈕,
你會發現,a.html已經跳轉到了百度首頁。
分析:我點擊的是a.html中嵌套的d.html部分的跳轉按鈕,結果是a.html中跳轉到了百度首頁,這就解釋了"top.location.href是最外層的頁面跳轉"的意思。