2009-09-02 6 views
1

요청시 div를 축소하려고 시도하지만 setTimeout 함수가 콜백 함수를 성공적으로 호출하지 못합니다. 여기에 아래의 코드입니다 :왜이 setTimeout 콜백으로 오류가 발생합니까?

function newsFeed() { 

    this.delete = function(listingID) { 

     var listing = document.getElementById(listingID); 
     var currHeight = listing.offsetHeight; 

     var confirmDelete = confirm("Are you sure you'd like to delete this listing forever?"); 
     if (confirmDelete) { 
      this.collapse(listingID,currHeight,currHeight,100); 
     } 

    } 

    this.collapse = function(listingID,orig_height,curr_height,opacity) { 
     var listing = document.getElementById(listingID); 
     var reduceBy = 10; 
     if(curr_height > reduceBy) { 
      curr_height = curr_height-reduceBy; 
      listing.style.overflow = "hidden"; 
      listing.style.height = (curr_height-40) + "px"; 

      if(opacity > 0) { 
       opacity = opacity - 10; 
       var opaque = (opacity/100); 

       listing.style.opacity=opaque;      
       listing.style.MozOpacity=opaque;     
       listing.style.filter='alpha(opacity='+opacity+')'; 
      } 

      setTimeout("this.collapse('"+listingID+"',"+orig_height+","+curr_height+","+opacity+")",1); 
     } 
    } 
} 

var newsFeed = new newsFeed(); 

는 다음과 같이 나는이 문서에서 전화 :

<div id="closeMe"> 
    <a onclick="newsFeed.delete('closeMe');">close this div</a> 
</div> 

을가 this.collapse 내에서의 setTimeout 기능에 도달하면 ... 그것은 오류 "this.collapse 함수가 아닙니다. "

답변

3

시간 초과로 전화를 걸면 기능을 종료하고 "this"는 더 이상 사용자가 생각하는 것을 참조하지 않습니다.

당신이처럼 폐쇄를 사용해야합니다

var self = this; 
setTimeout(function() 
{ 
    self.collapse(listingID, orig_height, curr_height, opacity); 
}, 1); 
+0

내가 이것을 newsFeed() 또는 this.collapse 함수 내에 넣을 수 있습니까? 일명 ...이 '실제로'언급해야 할 것은 무엇입니까? – johnnietheblack

+0

... 죄송합니다. 현재 self.collapse가 함수가 아닙니다. – johnnietheblack

+0

이 있습니다. RULE – johnnietheblack

0

시간 제한이 호출되면 this은 더 이상 원하는 것이 아닙니다. 다른 메커니즘 (아마도 ID 기반 검색)으로 원하는 DOM 요소를 참조해야합니다.

1

당신이보고있는 행동을 자바 스크립트의 범위 지정 문제 때문이다. JavaScript는 함수와 전역이라는 두 가지 범위 만 갖고 있습니다.

setTimeout() 호출을 수행 할 때 setTimeout() 호출로 인해 실행 된 코드에서 해당 상태를 사용하려면 전역 범위에서 변수를 설정해야합니다. 그것은 문제의 수정 일 것이다. Greg는 이미이를 수행 할 방법을 제안했습니다.

자세한 내용은 Mozilla 개발자 센터에서 setTimeoutCore JavaScript Reference 페이지를 참조하십시오.

관련 문제