2016-02-01 17 views
1

我下面一個簡單的嘖嘖這將有望打造出一個負責任的滑塊未捕獲的ReferenceError,但它不斷告訴我有在控制檯在一個叫advance()上的功能

這裏功能指向一個錯誤是簡單的HTML滑塊:

<div class="slider"> 
<div class="slide-viewer"> 
    <div class="slide-group"> 
     <div class="slide slide-1">1</div> 
     <div class="slide slide-2">2</div> 
     <div class="slide slide-3">3</div> 
     <div class="slide slide-4">4</div> 
    </div> 
</div> 
</div> 
<div class="slide-buttons"></div> 

這裏是JS - JQuery的已被列入前的腳本文件,所以我知道這是不是這裏的問題,但是當我點擊一個按鈕,它讓我在控制檯中的錯誤:

$(document).ready(function(){ 
$('.slider').each(function(){ 
    var $this = $(this); 
    var $group = $this.find('.slide-group'); 
    var $slides = $this.find('.slide'); 
    var buttonArray = []; 
    var currentIndex = 0; 
    var timeout; 

    function advance(){ 
     clearTimeout(timeout); 

     timeout = setTimeout(function(){ 
      if (currentIndex < ($slides.length - 1)){ 
       move(currentIndex + 1); 
      } else { 
       move(0); 
      } 
     }, 4000); 
    } 

    $.each($slides, function(index){ 
     var $button = $('<button type="button" class="slide-btn">&bull;</button>'); 
     if(index === currentIndex) { 
      $button.addClass('active'); 
     } 
     $button.on('click', function(){ 
      move(index); 
     }).appendTo('.slide-buttons'); 
     buttonArray.push($button); 
    }); 

advance(); 

}); 

function move(newIndex) { 
    var animateLeft, slideLeft; 

    advance(); 

    if ($group.is(':animated') || currentIndex === newIndex) { 
     return; 
    } 

    buttonArray[currentIndex].removeClass('active'); 
    buttonArray[newIndex].addClass('active'); 

    if (newIndex > currentIndex) { 
     slideLeft = '100%'; 
     animateLeft = '-100%'; 
    } else { 
     slideLeft = '-100%'; 
     animateLeft = '100%'; 
    } 

    $slides.eq(newIndex).css({left: slideLeft, display: 'block'}); 
    $group.animate({left: animateLeft} , function() { 
     $slides.eq(currentIndex).css({display: 'none'}); 
     $slides.eq(newIndex).css({left: 0}); 
     $group.css({left: 0}); 
     currentIndex = newIndex; 
    }); 
} 
}); 

它告訴我問題是Js的第40行,它指向第二次在腳本中看到advance()。任何幫助將不勝感激,因爲我不得不修改代碼已經有一些失敗,但這讓我難倒!授予Js不是我最強的語言!

+3

好,提前()中移動函數調用有其他每個循環的提前定義的訪問權限。範圍不一樣。 –

回答

2

問題是函數advance(){在foreach範圍內。它在您的move()函數內調用,它不在相同的範圍內。

最簡單的是將你的移動方法僅低於你的快進功能:

function advance(){ 
     clearTimeout(timeout); 

     timeout = setTimeout(function(){ 
      if (currentIndex < ($slides.length - 1)){ 
       move(currentIndex + 1); 
      } else { 
       move(0); 
      } 
     }, 4000); 
    } 

    function move(newIndex) { 
    //code for move function here