2015-01-19 7 views
0

Я привязываю функцию к событию.Контекст Javascript внутри функции

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

Проблема, которая возникает у меня, заключается в изменении моего контекста, и я не могу получить доступ к своим элементам. Я должен признать, что контекст Javascript ужасно запутанный мне:

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

setInterval выполняется в глобальном контексте, window, так this является window. Таким образом, кэш переменную и использовать его вместо

var that = this; 
var countup = setInterval(function() { 
    count++; 
    $(that).find('.countup').html(count + ' seconds!'); 
    if(count == count_to) { 
     count = 0; 
    } 
}, 750); 
Смежные вопросы