在使用框架(frameset)的頁面中,經常需要從一個子頁面刷新另一個子頁面。JavaScript 提供了多種等價的寫法可以達成。本文以一個上下分框的範例,示範如何操作。
frame.html 由上(top.html)下(bottom.html)兩個頁面組成:
<frameset rows="50%,50%"> <frame name=top src="top.html"> <frame name=bottom src="bottom.html"> </frameset>
在 top.html 中,可用以下任一句來刷新下方的 bottom.html:
window.parent.frames[1].location.reload();
window.parent.frames.bottom.location.reload();
window.parent.frames['bottom'].location.reload();
window.parent.frames.item(1).location.reload();
window.parent.frames.item('bottom').location.reload();
window.parent.bottom.location.reload();
window.parent['bottom'].location.reload();
為驗證刷新是否成功,可在 bottom.html 的 <body onload> 中放一個 alert,刷新時便會彈出提示。
· window:指當前頁面(此例為 top.html)。
· parent:指包含當前頁面的父框架頁(此例為 frame.html)。
· frames:一個代表框架內所有子頁面的陣列。
· item():回傳陣列中指定元素的方法。
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 區域,數字代表秒數:
<meta http-equiv="refresh" content="20"> <!-- 每隔 20 秒刷新一次 --> <meta http-equiv="refresh" content="20;url=https://www.example.com"> <!-- 20 秒後跳轉到指定網址 -->
也可用 JS 搭配 setTimeout 達到定時刷新:
function myrefresh(){ window.location.reload(); }
setTimeout('myrefresh()', 1000); // 指定 1 秒刷新一次
掌握這些語法,就能靈活地在框架頁面之間進行刷新與互動。不過隨著現代前端已大量以 iframe 與單頁應用取代傳統 frameset,這些技巧如今主要出現在維護舊系統的情境中。