[英]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.