萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 頁面刷新與跳轉完全指南:歷史導航、定時刷新與框架操作

瀏覽器歷史導航操作

JavaScript 提供多種方式操作瀏覽器歷史記錄,實現頁面前進、後退或跳轉至特定記錄點。

常用歷史導航方法

  • history.go(-1):返回上一頁;history.go(-2) 返回前兩頁。
  • history.back():等同於 history.go(-1)。
  • window.history.forward():前進至下一頁。
  • window.history.go(index 或 URL):跳轉至指定歷史索引或曾訪問過的 URL。

實際應用範例

<a href="javascript:history.go(-1);">返回上一頁</a>
<script>
if(!confirm('任務完成?')) { history.back(); }
</script>
onclick="window.location.href='list.aspx'" // 頁面跳轉

動態載入外部 JS 檔案

利用 document.write 動態注入 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>

頁面刷新的八種方式

方法說明
history.go(0)重新載入當前頁面
location.reload()標準刷新,可帶參數 true 強制從伺服器獲取
location = location重新賦值觸發刷新
location.assign(location)載入新文檔
document.execCommand('Refresh')IE 專用
window.navigate(location)IE 專用
location.replace(location)替換當前歷史記錄並刷新
document.URL = location.href修改 URL 觸發刷新

自動刷新與跳轉

Meta 標籤方式(放在 <head> 區塊)

<meta http-equiv="refresh" content="20">          // 20 秒自動刷新
<meta http-equiv="refresh" content="20;url=https://example.com"> // 20 秒後跳轉

JavaScript 定時器方式

<script>
function myRefresh() { window.location.reload(); }
setTimeout('myRefresh()', 1000); // 每秒刷新一次
</script>

ASP.NET 伺服器端輸出刷新腳本

// 刷新父視窗
Response.Write("<script>opener.location.reload();</script>");
// 或指定 URL
Response.Write("<script>opener.window.location.href = opener.window.location.href;</script>");
// 使用 navigate (IE)
Response.Write("<script>opener.window.navigate('target.aspx');</script>");

框架與視窗間刷新操作

// 刷新包含框架的父頁面
parent.location.reload();
// 子視窗刷新開啟它的父視窗
self.opener.location.reload();
// 或超連結方式
<a href="javascript:opener.location.reload()">刷新父頁</a>
// 刷新同級另一框架
parent.另一FrameID.location.reload();

視窗開啟/關閉時觸發父頁刷新

<body onload="opener.location.reload()">   <!-- 開啟時刷新 -->
<body onUnload="opener.location.reload()"> <!-- 關閉時刷新 -->
<script>window.opener.document.location.reload()</script>
copyright © 萬盛學電腦網 all rights reserved