我有以下 HTML/JS:
<html>
<body>
<script>
function foo(){
var html = "<iframe src=\"foo.html\" />";
document.getElementById('content').innerHTML=html;
}
function bar(){
var html = "<iframe src=\"bar.html\" />";
document.getElementById('content').innerHTML=html;
}
function show(){
alert(document.getElementById('content').innerHTML);
}
</script>
<button onclick="foo()">foo</button><br />
<button onclick="bar()">bar</button><br />
<button onclick="show()">test</button><br />
<div id="content"></div>
</body>
</html>
这种工作方式符合预期,即使在 IE 中也是如此。直到我按 F5。当我第一次点击 foo 时,我得到一个包含 foo.html
内容的 iframe , 正如预期的那样。然后我刷新,然后点击 bar。而不是获取 bar.html
的内容, 我看到了 foo.html
的内容.奇怪的是,当我单击测试 时,alert()
告诉我 src
iframe 的属性已正确设置为 bar.html
. Firefox 没有这样的问题。
为什么会发生这种情况,我该如何预防?
编辑: 我忘了说的是我不能把 iframe 放进去改变 src 属性。在我的真实情况下,有时我需要一个 <img>
而不是 <iframe>
.
最佳答案
使用这个 DOM
<div id="content" style='display:none;'>
<iframe id='contentFrame' src='' />
</div>
这是你的脚本
function foo() {
var contentDiv = document.getElementById('content');
var contentFrame = document.getElementById('contentFrame');
contentFrame.src = 'foo.html';
contentDiv.style.display='block';
}
我注意到 IE 和使用 innerHTML 时有一些奇怪的行为。我只会用它来清除内容 (innerHTML = "")。如果我想添加任何东西,我使用 HTMLElement.appendChild();它对我来说还没有失败。
关于javascript - IE缓存动态添加的iframe。为什么,我该如何预防?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/469177/