刷新 iframe 不外乎兩個方向:要嘛呼叫它的 reload,要嘛直接把 src 重新指派一次逼瀏覽器重載。
<script language="JavaScript"> window.location.reload(); </script>
location.reload([bForceGet]) 的參數是選填的:預設 false,會優先從瀏覽器快取取頁;傳 true 則以 GET 方式向伺服器要最新版本,效果等同使用者按 F5。
// 方法一:呼叫 iframe 內的 reload
document.getElementById('FrameID').contentWindow.location.reload(true);
// 方法二:重新指派 src
document.getElementById('youriframe').src = src;
完整範例:
<iframe id="myframe" width="100%" frameBorder="0" src="test.html" scrolling="no"></iframe>
<input type="button" onclick="javascript:refreshFrame();" value="Refresh Frame" />
<script type="text/javascript">
function refreshFrame(){
document.getElementById('myframe').contentWindow.location.reload(true);
}
</script>
把 src 原封不動再設一次,瀏覽器就會重新請求:
$('#iframe').attr('src', $('#iframe').attr('src'));
// 刷新包含該框架的頁面 parent.location.reload(); // 子視窗刷新開啟它的父視窗 self.opener.location.reload(); // 刷新另一個框架 parent.另一FrameID.location.reload();
小結:網路上大量流傳的 document.frames('ifrmname').location.reload() 寫法,在現代瀏覽器已經失效,請改用 contentWindow 或 src 重設的方式。