2015-01-19 6 views
0

이벤트에 함수를 바인딩하고 있습니다.함수 내의 JavaScript 컨텍스트

$('div.my_div').bind("mouseenter", timerFunc); 

문제는 내 컨텍스트가 변경되어 내 요소에 액세스 할 수 없다는 것입니다. 나는 자바 스크립트 문맥이 나에게 몹시 혼란 인정합니다 :

function timerFunc() { 
    //alert('Square ' + $(this).attr('data-somevalue') + ' named function called!'); 
    var count_to = 10; 
    var count = 0; 
    var countup = setInterval(function() { 
     count++; 
     $(this).find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square 
     //self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square 
     if (count == count_to) { 
      count = 0; 
     } 
    }, 750); 
} 

답변

2

대신 스토어 $(this)를 사용하여 중첩 된 함수에서 사용 :

function timerFunc() { 
    //alert('Square ' + $(this).attr('data-somevalue') + ' named function called!'); 
    var elem = $(this);//$(this) is stored in elem variable 
    var count_to = 10; 
    var count = 0; 
    var countup = setInterval(function() { 
     count++; 
    //so you can use it here in nested function 
     elem.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square 
     //self.find('.countup').html(count + ' seconds!'); // <-- trying to access THIS square 
     if (count == count_to) { 
      count = 0; 
     } 
    }, 750); 
} 
2

setIntervalwindow이다 국제적인 맥락에서 실행 도와주세요, 그래서 thiswindow입니다. 그래서 변수를 캐시하고 변수에

var that = this; 
var countup = setInterval(function() { 
    count++; 
    $(that).find('.countup').html(count + ' seconds!'); 
    if(count == count_to) { 
     count = 0; 
    } 
}, 750);