问题
I made an iFrame and would like to change it's source when it's load to next of 10 different sources:
It would look like this:
iframe loaded => change to example.com => iframe loaded => change to example1.com => iframe loaded => change to example2.com...
Is there any way to do this? ... I've tried a lot of stuff and stuck on something like this: (of course does not work at all)
<html>
<body>
<iframe onload="srca('http://www.com', 'a')" src="http://www.example.com"> </iframe>
<script>
function srca (src, load){
document.getElementsByTagName('iframe')[0].src = src
alert(document.getElementsByTagName('iframe')[0].src)
document.getElementsByTagName('iframe')[0].onload = load
}
function a(){
srca('http://js.do', 'b')
}
</script>
</body>
</html>
Thank you!
回答1:
I solved the problem like this: working jsfiddle here.
The javascript part is the following:
urls = ['http://www.example.com', 'http://www.com', 'http://js.do'];
position = 0;
element = document.getElementsByTagName('iframe')[0];
element.onload = frameLoaded;
next(); /* i.e. load the first */
function next() {
if (urls.length > position) {
element.src = urls[position];
position += 1;
}
}
function frameLoaded() {
setTimeout(next, 4000);
}
I got your code working. The problems were:
- hard to read :-P
- when you want pass around a named function, use it’s name, not a string of it, i.e.:
blabla.onload = a
blabla.onload = 'a'
is wrong
- the
onload
event fired before the script, i.e. the function you call is not defined yet- this is a common issue
- I fixed it by putting the script part before the
<iframe>
- the code of my solution is supposed to be executed by
body.onload
(jsfiddle does that)
来源:https://stackoverflow.com/questions/26561481/change-iframe-source-multiple-times