多次更改 iframe 源 [英] Change iframe source multiple times
问题描述
我制作了一个 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'
是错误的
- 这是一个常见问题
- 我通过将脚本部分放在
- 我的解决方案的代码应该由
body.onload
执行(jsfiddle 这样做)
- 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)
这篇关于多次更改 iframe 源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!