2012-04-19 4 views
0

파일로 리디렉션되는 카운트 다운 스크립트가 있습니다. 그것은 그것 안에 루프를 가지고 있고 변수는 그것이 한 번 달렸을 때 undifined된다.자바 스크립트 undifined 변수 after 루프

url 변수의 값을 유지하려면 어떻게해야합니까?

 <a id="" onClick="doTimer('http://www.domain.com/downloadfile.php?photo=foo.jpg')" href="#"><button id="download">Download this photo</button></a> 

     var timer_is_on=0; 
     var countdownfrom=5 
     var currentsecond=document.getElementById('countdown').innerHTML=countdownfrom+1 

     function countredirect(url) 
     { 
      if (currentsecond!=1) 
      { 
       currentsecond-=1 
       document.getElementById('countdown').innerHTML = currentsecond; 
      } 
      else 
      { 
       window.location=url 
       return 
      } 
      setTimeout("countredirect()",1000) 
     } 
     function doTimer(url) 
     { 
      if(!timer_is_on) 
      { 
       document.getElementById('download').innerHTML="Your download starts in <span id=\"countdown\"></span>seconds"; 
       timer_is_on=1; 
       countredirect(url) 
      } 
     } 
+0

어떤 변수가 정의되지 않았습니까? – JJJ

+3

** 문자열을'setInterval()'또는'setTimeout()'에 넘겨서는 안됩니다. 이렇게하는 것은'eval()'을 사용하는 것만 큼 나쁘다. 실제 변수를 전달하는 대신 문자열에 삽입해야하기 때문에 변수를 사용하자마자 코드를 읽을 수 없거나 안전하지 않을 수도있다. 적절한 해결책은'setInterval (function() {/ * your code *}}, msecs);'입니다. 'setTimeout()'도 마찬가지이다. 인자없이 하나의 함수를 호출하기를 원한다면, 함수 이름 바로 뒤에'setInterval (someFunction, msecs);'(함수 이름 뒤에 ** ** **'() – ThiefMaster

+0

먼저 dotimer 함수에서 사용하는 url 변수. – 9edge

답변

5
setTimeout("countredirect()",1000) 

당신은 당신의 countredirect 기능에 어떤 인자를 전달하지 않습니다.

문자열을 setTimeoutsetInterval으로 전달하는 것은 일반적으로 좋지 않은 아이디어입니다 (모든 종류의 범위 문제가 발생 함). 대신 함수를 전달합니다 새로운 브라우저에서

setTimeout(function() { 
    countredirect(url); 
}, 1000); 

을 (또는 심으로) 당신은 또한 .bind()[MDN] (bind 반환 새로운 기능)를 사용할 수 있습니다 : 다시 예약하는 함수를

setTimeout(countredirect.bind(null, url), 1000); 
0

다른 방법을 :

setTimeout(countredirect.bind(null, url), 1000);