常用的location.href的幾種形式:
self.location.href;
window.location.href; this.location.href;
location.href;
parent.location.href;
top.location.href;
舉例:
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;
運行a.html,貼圖一如下:
分析:我點擊的是a.html中嵌套的d.html部分的跳轉按鈕,結果是a.html中跳轉到了百度首頁,這就解釋了"top.location.href是最外層的頁面跳轉"的意思。
在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"; }
再次運行a.html,點擊那個"跳轉" 按鈕,運行結果貼圖二如下:
對比圖一和圖二的變化,你會發現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是最外層的頁面跳轉"的意思。