jQuery.each和变量范围

时间:2013-07-16 18:15:04

标签: jquery

$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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

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