DIV CSS 佈局教程網

JavaScript 頁面刷新與跳轉大全:history、location 與定時重載
編輯:JavaScript綜合知識     

「刷新」「跳轉」「回到上一頁」這三件事在 JavaScript 裡各有好幾種寫法,行為細節卻不盡相同。這份整理按用途分類,方便對照查閱。

一、返回上一頁與前進

history.go(-1);   // 回上一頁
history.go(-2);   // 回兩頁
history.back();   // 回上一頁
window.history.forward();  // 前進一頁
window.history.go(1);      // 前進一頁,也可傳入曾造訪過的 URL
<a href="javascript:history.go(-1);">向上一頁</a>

<!-- 搭配確認視窗 -->
<script language="javascript">
if (!confirm('完成任務?')) { history.back(); }
</script>

二、頁面跳轉

onclick="window.location.href='list.aspx'"

三、刷新頁面的八種寫法

history.go(0)
location.reload()
location = location
location.assign(location)
document.execCommand('Refresh')
window.navigate(location)   // 僅 IE 支援
location.replace(location)
document.URL = location.href

實務上最常用的其實只有前兩種。location.reload() 語意最清楚;history.go(0) 在多數瀏覽器中等價,但遇到表單重送確認時行為可能不同。

四、自動刷新與自動跳轉

最省事的做法是用 meta 標籤,寫在 <head> 內:

<!-- 每 20 秒重新載入目前頁面 -->
<meta http-equiv="refresh" content="20">

<!-- 20 秒後跳到指定網址 -->
<meta http-equiv="refresh" content="20;url=https://www.example.com">

要用 JavaScript 控制的話:

<script language="JavaScript">
function myrefresh() {
  window.location.reload();
}
setTimeout('myrefresh()', 1000);  // 每 1 秒刷新一次
</script>

更好的寫法是改用 setInterval 並記下計時器 ID,需要時用 clearInterval 停掉,避免頁面卸載後還在跑:

var timer = setInterval(function () {
  window.location.reload();
}, 60000);

// 需要停止時
clearInterval(timer);

五、刷新父窗口(彈出視窗情境)

// 1
this.response.write("<script>opener.location.reload();</script>");

// 2
this.response.write("<script>opener.window.location.href = opener.window.location.href;</script>");

// 3
Response.Write("<script language=javascript>opener.window.navigate('你要刷新的頁.asp');</script>");

六、框架相關的刷新語句

// 刷新包含本框架的整個頁面
<script language="JavaScript">
  parent.location.reload();
</script>

// 子視窗刷新開啟它的父視窗
<script language="JavaScript">
  self.opener.location.reload();
</script>

// 刷新另一個框架
<script language="JavaScript">
  parent.另一FrameID.location.reload();
</script>

開窗/關窗時觸發:

<body onload="opener.location.reload()">    <!-- 開窗時刷新 -->
<body onUnload="opener.location.reload()">  <!-- 關閉時刷新 -->

<script language="javascript">
window.opener.document.location.reload()
</script>

七、一個實用的小技巧:動態載入外部 JS

需要依條件決定要不要載入某支程式時,用 document.write 拼標籤是常見做法,但字串裡的 </script> 必須拆開寫,否則會提早結束目前的 script 區塊:

<script type="text/javascript">
if (typeof SWFObject == "undefined") {
  document.write('<scr' + 'ipt type="text/javascript" src="/scripts/swfobject-1.5.js"></scr' + 'ipt>');
}
</script>

現代寫法建議改用動態建立節點的方式,不阻塞頁面解析:

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = '/scripts/swfobject-1.5.js';
document.head.appendChild(s);

最後提醒:location.replace() 與 location.href = 的關鍵差別在於前者不會留下歷史紀錄,跳轉後按返回鍵不會回到原頁。做「轉址提示頁」時,用 replace 才是正確選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved