我想重新加载一个<iframe>使用JavaScript。到目前为止,我发现最好的方法是将iframe的src属性设置为自身,但这不是很干净。什么好主意吗?
当前回答
如果使用jQuery,这似乎是可行的:
$('#your_iframe').attr('src', $('#your_iframe').attr('src'));
其他回答
现在让这个工作在chrome 66,试试这个:
const reloadIframe = (iframeId) => {
const el = document.getElementById(iframeId)
const src = el.src
el.src = ''
setTimeout(() => {
el.src = src
})
}
在我的例子中,简单地替换iframe元素的src属性并不能令人满意,因为在加载新页面之前,人们会看到旧的内容。如果你想提供即时的视觉反馈,这种方法会更好:
var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
iframeEl.src = url;
}, 10);
document.getElementById('some_frame_id').contentWindow.location.reload();
注意,在Firefox中,window.frames[]不能通过id索引,而是通过名称或索引
另一个解决方案。
const frame = document.getElementById("my-iframe");
frame.parentNode.replaceChild(frame.cloneNode(), frame);
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;
}