重新加载/刷新 iframe 的最佳方法是什么
假设用户创建了一个网页。现在他有一个包含 IFrame 和按钮的网页。一旦用户按下按钮,他/她需要将 IFrame 重新加载/刷新。我们将在本文中找到如何实现这一点。
以下语法适用于两种情况:IFrame 是从相同域加载的情况和 IFrame 不是从相同域加载的情况。
语法:
document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);
注意: 在Firefox中,如果你要使用window.frames[]
,可能无法通过id来索引。因此,你必须通过索引或名称来进行索引。
示例1:
<!DOCTYPE html>
<html>
<head>
<style>
iframe {
width: 786px;
height: 600px;
border: 0;
overflow: hidden;
}
</style>
</head>
<body>
<center>
<h2 style="color:green">GeeksforGeeks</h2>
<h4 style="color:purple">Reload / Refresh an iframe</h4>
<iframe id="iframeid"
src="https://ide.geeksforgeeks.org/"
width="600"
height="450"
frameborder="0"
style="border:0"
allowfullscreen>
</iframe>
<input type="button"
id="btn"
value="Refresh" />
<script>
function reload() {
document.getElementById('iframeid').src += '';
}
btn.onclick = reload;
</script>
</center>
</body>
</html>
输出:
刷新前:
刷新后:
示例2:
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
}
iframe {
width: 786px;
height: 600px;
border: 0;
overflow: hidden;
}
</style>
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<h4 style="color:purple">Reload / Refresh an iframe</h4>
<iframe id="iframeid"
src="Map Source"
width="600"
height="450"
frameborder="0"
style="border:0"
allowfullscreen>
</iframe>
<input type="button"
id="btn"
value="Refresh" />
<script>
function reload() {
document.getElementById('iframeid').src += '';
}
btn.onclick = reload;
</script>
</body>
</html>
输出:
当加载代码时:
运行原理: