ifelse statement with iFrames
I have an iframe and i would like to make an if co开发者_StackOverflow社区ndition that if the iframe source is equal to a speciefied page a div should show:
Example
if(getElementById('iframe').src = 'someurl'){
getElementById('div').style.display. = 'block';
}
The Problem
I am not an expert in JS but when I use this script the iframe loads "someurl" automatically asoon as the main page is loaded, which I don't want, I want the div to be displayed when the iframe source changes to "someurl" via a link. The link is working fine and it changes the iframe src but the if statement isn't working.
=
is an assignment==
is an equality test===
is an equality test without type casting (and is generally prefered to==
Use ===
, not =
.
Then you need to reference getElementById
correctly. It is a method of the document
object, not a global.
Use document.getElementById
not getElementById
Then, you'll need to get rid of the trailing .
character from your display property.
Then, assuming you want to update this when a link in the frame is followed and not just when a link in the current page is followed, you need to rerun the function periodically to see if it has changed.
setInterval(yourFunctionName, 5000);
Then, since the page might move away from the URL you are looking for, you need to add an else statement
function yourFunctionName () {
var div = document.getElementById('div'); /* Really? Your unique ID for a specific div is 'div'?! */
if(document.getElementById('iframe').src === 'someurl'){
div.style.display = 'block';
} else {
div.style.display = 'none';
}
}
if(document.getElementById('iframe').src == 'someurl'){
document.getElementById('yourdiv').style.display = 'block';
}
use ==
instead of =
you are assign value to the src instead of checking for condition.
use ==
or ===
You have error in
if(getElementById('iframe').src = 'someurl')
=
is assignment, but you should check condition. Use ==
. You can swap condition, to eliminate errors, like this. Here is an example:
if('someurl' == getElementById('iframe').src)
The basick idea is than constant should be left part of comparision. And if you accidentally write assignment instead of comparison, i'll get more clear error.
精彩评论