1
$grid.find( 'div.bb-bookblock' ).each( function( i ) 
{                               
    var $bookBlock = $(this),
        $nav = $bookBlock.next(),
        $navNext = $nav.find('.bb-nav-next'),
        $navPrev = $nav.find('.bb-nav-prev'),
        $navFirst = $nav.find('.bb-nav-first'),
        $navLast = $nav.find('.bb-nav-last'),
        $playStop =  $nav.find('.bb-nav-play-stop'),
        isPlaying = false,
        autoplayTimer = null,
        bb = $bookBlock.bookblock( 
        {
            speed : 600,
            shadows : false
        });

});

.each 函数内的所有变量是否仅在循环内具有作用域?例如 autoPlayTimer 将是 setInterval 的结果。我想确保我没有覆盖变量。看起来它工作正常,但我想确保我理解$().each

4

2 回答 2

4

Javascript 中的变量有functional scope.

所以在本地声明的所有变量都只能在$.each because of the callback that is a function.

$grid.find('div.bb-bookblock').each(function (i) {
    var $bookBlock = $(this),
        $nav = $bookBlock.next(),
        autoplayTimer = null;

    bb = $bookBlock.bookblock({
        speed: 600,
        shadows: false
    });
    console.log($bookblock) // logs the current jQuery object in iteration
    console.log($nav) // logs the next element
    console.log(autoplayTimer) // null or the value if available
});

console.log($bookblock) // undefined
console.log($nav) // undefined
console.log(autoplayTimer) // undefined
于 2013-07-16T18:16:54.867 回答
2

在函数中定义的变量总是只在这个函数的范围内。这不是 each() 的问题,而是function(i) {...}.

于 2013-07-16T18:17:33.073 回答