我正在将一个函数绑定到一个事件。
$('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);
}
请帮忙
答案 0 :(得分: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);
答案 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);
}