2011-05-15 10 views
0

다른 JavaScript/jQuery 문제가 있습니다. 최소한의 예는 다음과 같습니다. div가 생겼고 마우스가 들어가면 JavaScript가 실행되기를 원합니다. 하지만 몇 가지 이유로 (실제로는 div가 여러 개 있고 각 데이터를 보관해야 함) 콜백의 핸들러로 객체를 사용하고 싶습니다. 여기에 작은 예는 다음과 같습니다 문서가로드 될 때개체 메서드를 콜백으로 사용

function handler($thediv) 
{ 
    this.somedata = 8; 

    $thediv.mouseenter(function() { this.callback(); }); 
} 

handler.prototype.callback = function() 
{ 
    alert(somedata); 
} 

객체가 생성됩니다

$(document).ready(function() { 
    new handler($("div")); 
}); 

아무런 반응이 없습니다 - 생성자가 실행되는 것을 제외하고. 지금 시도하고 몇 시간 씩 검색했지만,이 문제를 해결할 수는 없습니다 ... 아마도 사소한 일일까요?!? 사전에

감사합니다,
요스트

편집 : 완전한 예.

<html> 
<script type="text/javascript" src="jquery-1.6.js"></script> 
</head> 
<body> 

    <div> 
    blah blahasdasdadsssssssssssssss 
asddddddddddddddddddddddddddd 
    </div> 
</body> 
<script type="text/javascript"> 
    $(document).ready(function() { 
    new handler($("div")); 
    }); 

    function handler($thediv) 
    { 
    this.somedata = 8; 

    $thediv.mouseenter(this.callback); 
    } 

    handler.prototype.callback = function() 
    { 
    alert(somedata); 
    } 

    </script> 
</html> 

답변

3

여기에서 가장 큰 문제는 다양한 상황에서 this을 사용하는 것입니다. mouseenter 함수 내에서 this은 개체가 아니라 div를 참조합니다.

이 작동합니다 :

http://jsfiddle.net/Nx5c7/

function handler($thediv) 
{ 
    this.somedata = 8; 
    this.theID=$thediv.attr("id"); 

    var obj=this; 

    $thediv.mouseenter(function() { 
     obj.callback(); 
    }); 
} 

handler.prototype.callback = function() 
{ 
    alert(this.theID + " : " + this.somedata); 
} 
+0

이 감사합니다 :-) 속임수를 썼는지! – Jost

관련 문제