2008-12-17 140 views
0

我正在尝试在幻灯片之间暂停幻灯片。所以我试图使用setTimeout语句,如下所示。这被写入交换2.jpg为1.jpg点击按钮10秒的暂停。但它现在可以工作。谁能帮我。谢谢。使用setTimeout - 如何传递参数?

<html> 
<head> 
<script type="text/javascript"> 
var t; 
function swap(newImage) { 
    var fileName=newImage.toString()+".jpg" 
    document.slideshow.src=fileName 
    t=setTimeout("swap()",10000) 
} 
</script> 
</head> 
<body> 
    <img name="slideshow" src="1.jpg" width="450" height="335" /> 
    <br /><br /> 
    <input type="button" onClick="swap('2')" value="Change image" /> 
    <br /><br /> 
</body> 
</html> 
+0

那么会发生什么?显示更多代码。我希望你的代码看起来不像你在这里发布的内容。 – Strelok 2008-12-17 00:45:42

+1

这实际上没有意义,因为setTimeout操作没有定义参数,所以它如何有效地执行任何操作? – 2008-12-17 00:49:34

+0

在[我怎样才能将参数传递给setTimeout()回调?](更好地详细回答?)(http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-toa-a- settimeout-callback) – 2015-04-17 07:25:48

回答

2

您的交换功能需要一个参数,所以它不会与setTimeout一起使用。

+0

噢耶哈大声笑:)这将实际上:) – Strelok 2008-12-17 00:50:43

6

这里有一些错误。首先,不推荐在setTimeout的第一个参数中对其代码进行评估。更好地传递回调:

setTimeout(function() { swap(); },10000); 
//Or 
setTimeout(swap,10000); //Passing the actual function as the callback 

其次,您在超时内调用不带参数的swap()方法。它应该传入一个新的图像文件名(可能是通过声明一个文件名数组),或者检查参数是否设置。

function swap(newImage,element) { 
    if(newImage) { 
     var fileName = newImage.toString()+".jpg"; 
     element.src = fileName; 
    } 
    t=setTimeout(this,10000) 
} 

这个函数在第一次运行后显然不会做任何事情(因为没有提供新的图像文件名)。使用数组可以迭代多个文件名:

var images = ['1.jpg','2.jpg','3.jpg']; 
var slideshow = function(element, images, index) { 
    if(!index || ((index + 1) > images.length)) index = 0; 
    element.src = images[index]; 
    t = setTimeout(function(){ 
     slideshow(element, images, index + 1); 
    },10000) 
}; 

//Fetch the image element the slideshow is running on 
var element = document.slideshow; 
slideshow(element, images); 

这将继续在数组中的图像之间切换,直到超时被取消。

-1

JavaScript没有必要做幻灯片放映。所有您需要做的就是把每一个图像到一个单独的页面,那么这一行添加到每个页面的顶部的< head>部分:

<meta http-equiv="refresh" content="10;url=NextPage.html"/> 

“10”秒之前等待的秒数转到下一页,“NextPage.html”是包含要显示的下一个图像的页面的链接。