多次更改 iframe 源 [英] Change iframe source multiple times

查看:25
本文介绍了多次更改 iframe 源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 iFrame,并希望在加载到 10 个不同来源中的下一个时更改它的来源:

I made an iFrame and would like to change it's source when it's load to next of 10 different sources:

它看起来像这样:

iframe 加载 => 更改为 example.com => iframe 加载 => 更改为 example1.com => iframe 加载 => 更改为 example2.com...

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>

谢谢!

推荐答案

我是这样解决的:在这里工作 jsfiddle.

I solved the problem like this: working jsfiddle here.

javascript 部分如下:

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:

  • 难以阅读:-P
  • 当你想传递一个命名函数时,使用它的名字,而不是它的字符串,即:
    • blabla.onload = a
    • blabla.onload = 'a' 是错误的
    • 这是一个常见问题
    • 我通过将脚本部分放在