[英]Why does setInterval seem to have scope issues in my jQuery plugin?
很抱歉,这不是更具体,但我无法隔离问题。
我编写了一个非常简单的 jQuery 插件,它可以在设定的时间间隔内通过 div 滚动图像或其他元素,如轮播。 我希望这个插件可以在一个页面上处理多个实例,但是当我在多个元素上调用它时,只有最后一个初始化的元素会滚动。 我认为我使用 setInterval 的方式是原因,但我不明白为什么。
滚动用的function如下,上面链接了完整源码。
function scrollRight() {
// Don't animate if the mouse is over the scrollah
if (hovering) { return; }
/* If we're at the end, flip back to the first image
* before animating, lest we view blankness in the wrapper
*/
if (position === nChildren) {
position = 0;
$wrapper.css('left', '0px');
}
// Animate to the next view
position++;
$wrapper.animate({
left: position*-width+'px'
}, 1000, 'swing', function() {
// Animation complete.
});
}
setInterval(scrollRight, 5000);
那么为什么这个插件的单个实例不再滚动一次呢?
我想如果你改变$wrapper = $this.find('.wrapper');
到var $wrapper = $this.find('.wrapper');
它可能会起作用。
前几天从 Stack Overflow 学到了这一点:不使用var
关键字的变量在 scope 中是隐式全局的,所以我认为每个滚动条都覆盖了相同的全局$wrapper
变量。
编辑:可能还想做var $this = $(this);
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.