下面是一个简单的滑块代码,我想了解的变量函数闭包是如何工作的?功能的可调关闭
(function($) {
var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
imgs = sliderUL.find('img'),
imgWidth = imgs[0].width, // 600
imgsLen = imgs.length, // 4
current = 1,
totalImgsWidth = imgsLen * imgWidth; // 2400
$('#slider-nav').show().find('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth; // 600
// update current value
**(direction === 'next') ? ++current : --current;
// if first image
if (current === 0) {
current = imgsLen;
loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
direction = 'next';
} else if (current - 1 === imgsLen) { // Are we at end? Should we reset?
current = 1;
loc = 0;
}
transition(sliderUL, loc, direction);**
});
function transition(container, loc, direction) {
var unit; // -= +=
if (direction && loc !== 0) {
unit = (direction === 'next') ? '-=' : '+=';
}
container.animate({
'margin-left': unit ? (unit + loc) : loc
});
}
})(jQuery);
在这一部分:
$('#slider-nav').show().find('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth; // 600
// update current value
(direction === 'next') ? ++current : --current;
// if first image
if (current === 0) {
current = imgsLen;
loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
direction = 'next';
} else if (current - 1 === imgsLen) { // Are we at end? Should we reset?
current = 1;
loc = 0;
}
transition(sliderUL, loc, direction);
});
在if(当前=== 0)块,变量current,loc和方向在第一个块中被更改后更新,然后它们被传递到下面的转换函数?
我认为,如果else if(current - 1 === imgsLen)为true,那么current和loc会写入先前分配给它们的值,然后传递给transitions函数?
谢谢,这澄清了很多。非常好的解释! – nick 2012-03-04 18:16:40