location.href的用法


一:提出問題

使用js的同學一定知道js的location.href的作用是什么,但是在js中關於location.href的用法究竟有哪幾種,究竟有哪些區別,估計很多人都不知道了。

二:常見的幾種形式

目前在開發中經常要用到的幾種形式有:

//var url = "www.baidu.com";
self.location.href="url"; //1.僅在本頁面打開url
window.location.href="url"; //2.當前頁面打開URL頁面
this.location.href="url"; //3.用法和self.location.href一直
location.href="url"; //4.當前頁面打開URL頁面 
parent.location.href="url"; //5.在父窗口打開此url窗口
top.location.href="url";//6.在頂層頁面打開url(跳出框架)

三:代碼部分

那么,這幾種形式的跳轉究竟有什么區別呢?

直接講定義,你肯定不會理解透徹,下面我來貼四個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

運行a.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"; } 

再次運行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是最外層的頁面跳轉"的意思。

五:總結

看完上面的講解之后,在來看看下面的定義你就會非常明白了:
"top.location.href"是最外層的頁面跳轉
"window.location.href"、"location.href"是本頁面跳轉
"parent.location.href"是上一層頁面跳轉.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM