我遇到了setTimeout的问题。我也试过setInterval。我希望JS只是暂停或睡觉。
理论上,此代码应该从数组中写入第一个链接,等待3秒,写入下一个,依此类推。但它甚至不会调用该函数。
<html>
<head></head>
<body>
<a href="http://www.google.com">Google</a>
<a href="http://www.thinkgeek.com">ThinkGeek</a>
<a href="http://www.themetapicture.com">The Meta Picture</a>
<iframe src="http://www.google.com" id="myid" name="main" width="1024" height="768">
</iframe>
<script>
function getLinksArray(){
for(var i=0; i < document.links.length; i++){
var linx = document.links[i].href;
setTimeout("openLinks(linx)"),3000);
}
}
function openLinks(link){
document.write(link + "<br />");
}
window.onload = getLinksArray();
</script>
</body>
</html>
我的问题的第二部分是将iframe的src更改为链接(而不是编写它们)。我只是使用document.write
进行测试以延迟工作。
我已经尝试了document.getElementById("myid").src = link;
,它根本不会做任何事情。几乎就像iframe甚至不存在一样。
我不是专业人士,所以我在这里希望得到专业人士的帮助。 ;)提前致谢。
答案 0 :(得分:0)
你主要有问题,因为你不能那样打电话给setTimeout
。
你应该传递一个函数,它需要传递一个绑定变量,即
for (var i=0; i < document.links.length; i++) {
var linx = document.links[i].href;
setTimeout(function(linx) {
return function() {
openlinks(linx);
}
}(linx),3000);
}
内部函数是将循环变量传递给回调的“标准”Javascript方法之一。如果它没有意义,你需要一个很多更多的帮助...
答案 1 :(得分:0)
首先,永远不要将字符串传递给setTimeout
。
// old and busted
setTimeout("openLinks(linx)"),3000);
// new hotness
setTimeout(function() {
openLinks(linx)
}, 3000);
其次,生成函数的循环需要一些额外的帮助。您需要在闭包中捕获循环的值,否则值将在使用它的函数执行之前更改。
function getLinksArray() {
for (var i = 0; i < document.links.length; i++) {
var linx = document.links[i].href;
// create a closure for each loop iteration
(function(linx) {
setTimeout(function() {
openLinks(linx);
}, 3000);
}(linx));
}
}
function openLinks(link) {
// document.write(link + "<br />");
// document.write is also bad for a number of reasons
someElement.innerHTML += link + "<br />"
}
window.onload = getLinksArray();
封闭魔法所做的是创建全新的局部变量,仅与在循环的每次迭代中创建的函数共享。没有它你实际上有一些看起来更像这样的东西:
var linx; // var linx in the loop actually get hoisted to outside the loop!
for(var i=0; i < document.links.length; i++){
linx = document.links[i].href;
setTimeout(function() {
openLinks(linx)
},3000);
}
}
看一下,您可以看到循环将完成运行,linx
将设置该循环的最后一个值,然后您的第一个超时将使用linx
的值触发所有的超时分享。
创建并执行一个函数,传入该值可以防止该提升和共享。
答案 2 :(得分:0)
感谢大家的帮助,我有一个最终的工作产品:
<html>
<head></head>
<body>
<a href="http://www.google.com">Google</a><br />
<a href="http://www.thinkgeek.com">ThinkGeek</a><br />
<a href="http://www.themetapicture.com">The Meta Picture</a>
<iframe src="http://www.google.com" id="myid" name="main" width="1024" height="768">
</iframe>
<script>
function getLinksArray() {
for (var i = 0; i < document.links.length; i++) {
var linx = document.links;
(function loadLink(i) {
setTimeout(function () {
document.getElementById("myid").src = linx[i].href;
if(linx[++i])
{
loadLink(i);
}
}, 20000)
})(0);
}
}
window.onload = getLinksArray();
</script>
</body>
</html>