cat*_*use 2 javascript recursion lambda closures functional-programming
这是我们使用的幻灯片:
http://www.littlewebthings.com/projects/blinds/
这是JS文件:
http://www.littlewebthings.com/projects/blinds/js/jquery.blinds-0.9.js
但是,此幻灯片显示没有使其自动浏览每个图像的设置.您仍然必须单击它下面的数字才能看到图像.有人知道要添加到javascript代码中的内容,以使其自动浏览每个图像吗?
谢谢!
eco*_*sis 12
此解决方案使用闭包和递归.
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
Run Code Online (Sandbox Code Playgroud)
我们在这里做的是将内部函数暴露在timer定义它的函数之外(SlideChanger).此函数(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
Run Code Online (Sandbox Code Playgroud)
JavaScript是一种很好的语言,具有许多函数式编程结构,例如高阶函数(创建函数或接受函数作为参数的函数)和匿名函数.有关详细信息,请访问http://www.ibm.com/developerworks/web/library/wa-javascript.html