window.location.href的用法

來源:互聯網
上載者:User

標籤:

無論在靜態頁面還是動態輸出頁面中window.location.href都是不錯的用了跳轉的實現方案 

javascript中的location.href有很多種用法,主要如下。

self.location.href="/url" 當前頁面開啟URL頁面
location.href="/url" 當前頁面開啟URL頁面
windows.location.href="/url" 當前頁面開啟URL頁面,前面三個用法相同。
this.location.href="/url" 當前頁面開啟URL頁面
parent.location.href="/url" 在父頁面開啟新頁面
top.location.href="/url" 在頂層頁面開啟新頁面

如果頁面中自訂了frame,那麼可將parent self top換為自訂frame的名稱,效果是在frame視窗開啟url地址

此外,window.location.href=window.location.href;和window.location.Reload()和都是重新整理當前頁面。區別在於是否有提交資料。當有提交資料時,window.location.Reload()會提示是否提交,window.location.href=window.location.href;則是向指定的url提交資料

在寫ASP.Net程式的時候,我們經常遇到跳轉頁面的問題,我們經常使用Response.Redirect 做ASP.NET架構頁跳轉,如果客戶要在跳轉的時候使用提示,這個就不靈光了,如:

 

代碼如下:
Response.Write("< script>alert(‘恭喜您,註冊成功!‘);< /script>"); 
Response.Redirect("main.html");  

這時候我們的提示內容沒有出來就跳轉了,和Response.Redirect("main.html");沒有任何區別。

這時我們採用下面代碼實驗一下:

ASP.NET架構頁跳轉的另一實現

  代碼如下:Response.Write("< script language=javascript>alert(‘恭喜您,註冊成功!‘)< /script>"); 
Response.Write("< script language=javascript>window.location.href=‘main.html‘< /script>");

這個即實現了我們的要求,在提示後,跳轉頁面。

最重要的是window.location.href 語句可以實現一個架構的頁面在執行伺服器端代碼後重新整理另一個架構的頁面(Response.Redirect無法達到,至少我沒有發現):

如:index.htm頁面中有二個架構,分別為 frameLeft和frameRight,在frameRight頁面中執行伺服器端代碼後重新整理frameLeft中的頁面。

先前最常見的是註冊之後,自動重新整理登陸框,讓登陸框換成已登陸頁面,只要在註冊成功的代碼之後加上一段,即可以實現重新整理另個架構的頁面。代碼如下:

 

代碼如下:

Response.Write("< script language=javascript>alert(‘恭喜您,註冊成功!‘)< /script>"); 
Response.Write("< script language=javascript>window.parent.frameLeft.location.href=‘main.html‘< /script>");  

這樣就搞定了ASP.NET架構頁跳轉中斷的問題。其實asp、php中一般都使用這種方式。


"window.location.href"、"location.href"是本頁面跳轉
"parent.location.href"是上一層頁面跳轉
"top.location.href"是最外層的頁面跳轉

舉例說明:

如果A,B,C,D都是jsp,D是C的iframe,C是B的iframe,B是A的iframe,如果D中js這樣寫

"window.location.href"、"location.href":D頁面跳轉
"parent.location.href":C頁面跳轉
"top.location.href":A頁面跳轉

如果D頁面中有form的話,

<form>: form提交後D頁面跳轉
<form target="_blank">: form提交後彈出新頁面
<form target="_parent">: form提交後C頁面跳轉
<form target="_top"> : form提交後A頁面跳轉
 
關於頁面重新整理,D 頁面中這樣寫:

"parent.location.reload();": C頁面重新整理 (當然,也可以使用子視窗的 opener 對象來獲得父視窗的對象:window.opener.document.location.reload(); )

"top.location.reload();": A頁面重新整理

window.location.href的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.