views:

920

answers:

3

I have the following 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>

This sort of works as expected, even in IE. Until I hit F5. When I first click foo, I get an iframe with the contents of foo.html, as expected. I then refresh, and hit bar. Instead of getting the contents of bar.html, I see the contents of foo.html. Strangely, when I click test, the alert() tells me the src attribute for the iframe is correctly set to bar.html. Firefox has no such issue.

Why does this happen, and how do I prevent it?

edit: what I forgot to mention is that I can't put the iframe in and change the src attribute. In the real situation I have, sometimes I need an rather than an .

+2  A: 

Set the SRC of the Iframe instead of changing the innerHTML of its container:

html:

<iframe id="myFrame" src="about:blank" />

script:

document.getElementById('myFrame').src='foo.html'
Diodeus
+2  A: 

Use this DOM

<div id="content" style='display:none;'>

  <iframe id='contentFrame' src='' />

</div>

And this as your script

function foo() {
  var contentDiv = document.getElementById('content');
  var contentFrame = document.getElementById('contentFrame');

  contentFrame.src = 'foo.html';
  contentDiv.style.display='block';
}

I have noticed some weird behavior with IE and using innerHTML. I would only use it to clear the contents (innerHTML = ""). If I want to add anything, I use HTMLElement.appendChild(); it hasn't failed for me yet.

geowa4
+1  A: 

Have you tried changing the url in your generated iframe? E.g.

var randomNum = Math.random();
var html = "<iframe src=\"bar.html?rand="+randomNum+"\" />";

Even better, combine that with geowa4's appendChild() suggestion.

Ria