该解决方案使用关闭和递归。
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
我们这里做的是暴露出它被定义的函数(SlideChanger
)的内部函数timer
之外。该功能(timer
)可以访问SlideChanger
(index
和maxindex
)中定义的变量。
现在我们已经在封闭环境中设置了变量并且返回了调用者函数,我们可以在logic
中设置逻辑引擎。当logic
运行时,它使用index
和maxindex
来确定下一张应该显示哪张幻灯片,显示幻灯片,并安排自己再次运行。
当被调用时,返回函数调用logic
来让球滚动。然后,logic
通过调度自身以便在将来每次运行时重复无限期地运行。
因此,总而言之,我们呼吁SlideChanger
与数字参数x
。它会返回一个函数,在被调用后,将每隔x
秒更改幻灯片。
写出同样概念的另一种方法。
(function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
return function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
})(5)(); // get the function at five seconds per slide and run it
JavaScript是一个很好的语言与许多功能的编程结构如高阶函数(函数,要么创建函数或接受函数作为参数)和匿名函数。欲了解更多信息,请参阅http://www.ibm.com/developerworks/web/library/wa-javascript.html
感谢发布。但是,你能指导我在JS文件的哪个位置插入它吗? – catandmouse 2010-11-25 06:08:31
试试在jquery.blinds-0.9的底部。js – ecounysis 2010-11-25 07:17:30