I have an <iframe>
control on my page and I want to change it's target url (the url of the page displayed in the iframe) by a click on a hyperlink. The problem is that the iframe doesn't update on the click. I'm pretty sure I'm missing something, but I don't know what:
<script type="text/javascript">
var source = document.getElementById("CurrentlySelected")
function change(u) {
if (source.getAttribute("src") != u) {
source.setAttribute("src", u);
document.location.reload(true);
}
}
</script>
<ul>
<li><a href="#" onclick="change('http://www.somewebsite.com');">Website 1</a></li>
<li><a href="#" onclick="change('http://www.thiswebsite.net');">Website 2</a></li>
</ul>
<iframe id="CurrentlySelected" width="800px" height="600px" src="http://www.somewebsite.com"></iframe>
JS is not my forte, but I don't see a problem here... any ideas?
Another problem is that the background of the iframe isn't taking the same color of the website linked in its src attribute...
EDIT
The issue with the background color of the website in the iframe seems to b开发者_运维技巧e an issue with Google Chrome, anyone know about a fix?When you write document.location.reload(true)
, you are refreshing the parent page, resetting the <iframe>
to point to the original URL.
Remove that line; setting the src
attribute will already reload the frame.
Also, you're calling document.getElementById
before the <iframe>
element exists; you should move the <script>
block after the <iframe>
.
Try this...
<ul>
<li><a href="#" onclick="change('http://www.somewebsite.com');">Website 1</a></li>
<li><a href="#" onclick="change('http://www.thiswebsite.net');">Website 2</a></li>
</ul>
<iframe id="CurrentlySelected" width="800px" height="600px" src="http://www.somewebsite.com"></iframe>
<script type="text/javascript">
// now iframe is available...
var source = document.getElementById("CurrentlySelected")
function change(u) {
if (source.getAttribute("src") != u) {
source.setAttribute("src", u);
// NOT NEEDED: document.location.reload(true);
}
}
</script>
Is the problem your document.location.reload(true);
? If you're changing the iframe's URL but then reloading the page that contains the iframe, the iframe's URL will be set back to the state of what's in the host page's HTML.
精彩评论