2015-01-17 8 views
1

나는 그 객체를 선택하여 객체화하고 페이드하는 루프를 가지고 있지만 루프가 실행될 때 객체 ID는 마지막 엔트리에 머문다.자바 스크립트 설정 시간 초과 for 루프 내의 함수

var ordered = Array(elements.length); 
      var x = 0; 
      $('#' + that.options.slide_name + '_' + that.nextslide).children().each(function() { 
       ordered[x] = $(this); 
       $(this).fadeOut(1); 
       $(this).attr('id','current_slide_content_' + x); 
       x++; 
      }); 
//fade each element 
      var time = that.options.fade_speed/ordered.length 
      var overlap = time/that.options.fade_step; 
      //time = time + overlap; 
      var wait = 0; 
      var num = 0; 
      var i = null; 
      var funcs = Array(ordered.length); 
      for(var a = 0; a < ordered.length; a++){ 
       var w = wait; 
       var id = $('#current_slide_content_' + a); 
       window.setTimeout(function (event) { 
        id.fadeIn(time); 
        console.log(id); 
       },w); 
       //$('#current_slide_content_' + a).fadeIn(time); <-- on its own works, error is with the wait time 
       wait = time + wait; 
      } 

실제로 제한 시간 기능을 추가하는 최종 루프에 오류가있는 것으로 범위를 좁혔습니다.

foo_0 FOO_1 FOO_2

그러나 대신는 표시 :

for(var a = 0; a < ordered.length; a++){ 
       var w = wait; 
       var id = $('#current_slide_content_' + a); 
       window.setTimeout(function (event) { 
        id.fadeIn(time); 
        console.log(id); 
       },w); 
       //$('#current_slide_content_' + a).fadeIn(time); <-- on its own works, error is with the wait time 
       wait = time + wait; 
      } 

요소의 ID가 기록되면 그것되어야

FOO_2 FOO_2 FOO_2

나는 며칠 동안이 일을하고 몇 시간을 다시 시작했다. s, 각 Timeout 함수에 대해 id를 올바르게 포맷하는 방법은 무엇입니까?

+3

의 중복 가능성 [자바 스크립트 클로저 내부 루프 - 간단한 실제적인 예 (HTTP : //stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – JJJ

답변

2

시도해야

window.setTimeout((function(time_, id_){ 
    return function (event) { 
     id_.fadeIn(time_); 
     console.log(id_); 
    } 
})(time,id),w); 

이 함수의 범위에 timeid의 값을 저장하는 폐쇄입니다

+1

내부 'id.fadeIn'을'id_.fadeIn'으로 고치면 준비가 된 것처럼 보입니다. 가자;) –

+0

나는 그것이 단순한 무엇인가라고 믿을 수 없다. 고마워. –