三個頁面放在同一個視窗裡:main.htm 作為主頁,內含 left.htm 與 right.htm 兩個 iframe。
<html> <head><title>主視窗</title></head> <body> <div>主窗口</div> <iframe id="left" name="left" width="500px" height="300px;" src="left.htm"></iframe> <iframe id="right" name="right" width="100px" height="100px;" src="right.htm"></iframe> </body> </html>
<input onclick="onclickRefresh();" type="button" value="提交" />
<script type="text/javascript">
function onclickRefresh() {
parent.frames["left"].location.reload();
// window.left.location.reload(); 亦可
}
</script>
<div><input type="button" onclick="mainRefresh();" value="主提交" /></div>
<script type="text/javascript">
function mainRefresh() {
window.left.location.reload();
}
</script>
關鍵就是透過 parent.frames["name"] 取得目標 frame 的 window 物件,再呼叫它的 location.reload()。
寫起來確實輕鬆,可放到真實專案裡問題就浮現了。最典型的場景是左右樹、目錄樹——建立並載入一千個節點本身就相當耗資源,若每次互動都整頁 reload 左右兩邊,成本會非常可觀,使用者也會明顯感到卡頓。
比較合理的方向是局部更新:用 AJAX 只拉取變動的資料片段,而不是重載整棵樹;或搭配 jQuery 的 JSON 處理方式,做資料層級的增量更新。這樣既省頻寬,也避開了重建 DOM 的龐大開銷。
換句話說,跨 iframe 刷新這招適合 demo 與極簡單的頁面,一旦資料量上來,就該換成局部渲染的思維。千個節點等級的樹,值得為它重新設計載入策略。