在做頁面流轉時,返回上一頁、跳轉、刷新是再常見不過的操作。本文把 JavaScript 中相關的方法整理在一起,方便查閱。
// 返回上一頁
history.go(-1);
// 返回兩個頁面
history.go(-2);
// 等價寫法
history.back();
// 前進到下一頁
window.history.forward();
// 跳到指定頁數或訪問過的 URL
window.history.go(頁數);
例如一個返回鏈接:
<a href="javascript:history.go(-1);">向上一頁</a>
// 頁面跳轉
onclick="window.location.href='list.aspx'"
history.go(0)
location.reload()
location = location
location.assign(location)
document.execCommand('Refresh')
window.navigate(location)
location.replace(location)
document.URL = location.href
把下面的 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>
// 刷新包含該框架的頁面
parent.location.reload();
// 子窗口刷新父窗口
self.opener.location.reload();
// 刷新另一個框架的頁面
parent.另一FrameID.location.reload();
想在開窗或關窗時刷新父窗口,可在 body 中調用:
<body onload="opener.location.reload()"> 開窗時刷新
<body onUnload="opener.location.reload()"> 關閉時刷新
掌握這些方法,頁面前後跳轉、定時刷新、跨框架操作都能應對自如。