函数中的Javascript上下文

时间:2015-01-19 15:16:16

标签: javascript jquery

我正在将一个函数绑定到一个事件。

$('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 个答案:

答案 0 :(得分:2)

setIntervalwindow的全局上下文中执行,因此thiswindow。所以缓存变量并使用它来代替

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

答案 1 :(得分: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);
}