我想重新加载一个<iframe>使用JavaScript。到目前为止,我发现最好的方法是将iframe的src属性设置为自身,但这不是很干净。什么好主意吗?


当前回答

将空字符串附加到iFrame的src属性也会自动重新加载它。

document.getElementById('id').src += '';

其他回答

我有一个问题,因为我没有使用超时给页面时间更新,我将src设置为“,然后将其设置回原来的url,但什么都没有发生:

function reload() {
   document.getElementById('iframe').src = '';
   document.getElementById('iframe').src = url;
}

但是它没有重新加载网站,因为它是单线程的,第一个改变不做任何事情,因为这个函数仍然占用线程,然后它设置回原来的url,我猜chrome不重新加载是因为性能或其他什么,所以你需要做:

function setBack() {
   document.getElementById('iframe').src = url;
}
function reload() {
   document.getElementById('iframe').src = '';
   setTimeout(setBack,100);
}

如果setTimeout时间太短,它不工作,所以如果它不工作,尝试将它设置为500或其他东西,看看它是否工作。

这是在最新版本的chrome在写这篇文章的时候。

IE使用reload,其他浏览器使用set src。(重新装填对FF无效) 在IE 7、8、9和Firefox上测试

if(navigator.appName == "Microsoft Internet Explorer"){
    window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
    window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}
<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 
document.getElementById('iframeid').src = document.getElementById('iframeid').src

它将重新加载iframe,甚至跨域! 通过IE7/8, Firefox和Chrome测试。

注意:正如@user85461所提到的,如果iframe src URL中有一个散列,这种方法就不起作用了(例如http://example.com/#something)。

将空字符串附加到iFrame的src属性也会自动重新加载它。

document.getElementById('id').src += '';