我有一个contenteditable
div,当你输入它时,2秒后我会尝试改变它的背景颜色。
这是我的代码:
function changeFn(){
$(this).css('background','red')
console.log($(this).attr('id'));
}
var timer;
$("div.content").on("keypress paste", function () {
clearTimeout(timer);
timer = setTimeout(changeFn, 2000)
});
似乎我必须将$(this)传递给函数,因为它无法识别这是$。
当我在按键功能中设置背景颜色更改时,它可以正常工作。
jsFiddle:http://jsfiddle.net/uc8Tg/
答案 0 :(得分:1)
使用jQuery.proxy
设置函数的上下文:
function changeFn() {
$(this).css('background', 'red');
}
var timer;
$("div.content").on("keypress paste", function() {
clearTimeout(timer);
timer = setTimeout($.proxy(changeFn, this), 2000);
});
答案 1 :(得分:0)
function changeFn(){
$(this).css('background','red')
console.log($(this).attr('id'));
}
var timer;
$("div.content").on("keypress paste", function () {
clearTimeout(timer);
var self = this;
timer = setTimeout(function(){changeFn.call(self)}, 2000)
});
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call