Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在X秒后键入输入时更改背景色_Javascript_Jquery_Timer_Keypress - Fatal编程技术网

Javascript 在X秒后键入输入时更改背景色

Javascript 在X秒后键入输入时更改背景色,javascript,jquery,timer,keypress,Javascript,Jquery,Timer,Keypress,我有一个contenteditablediv,当您键入它时,2秒钟后我会尝试更改它的背景色 这是我的代码: function changeFn(){ $(this).css('background','red') console.log($(this).attr('id')); } var timer; $("div.content").on("keypress paste", function () { clearTimeout(t

我有一个
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)传递给函数,因为它无法识别这是哪一个$

当我在按键功能中设置背景颜色更改时,它会工作

jsiddle:

使用,它设置函数的上下文:

function changeFn() {
    $(this).css('background', 'red');
}
var timer;

$("div.content").on("keypress paste", function() {

    clearTimeout(timer);
    timer = setTimeout($.proxy(changeFn, this), 2000);
});
示例:

使用,用于设置函数的上下文:

function changeFn() {
    $(this).css('background', 'red');
}
var timer;

$("div.content").on("keypress paste", function() {

    clearTimeout(timer);
    timer = setTimeout($.proxy(changeFn, this), 2000);
});
示例:


非常感谢。我又一次从你身上学到了新东西。@jQuerybeast:很高兴一如既往地帮助你!非常感谢你。我又一次从你身上学到了新东西。@jQuerybeast:很高兴一如既往地帮助你!非常感谢。我将使用Andrew的答案,因为它使用更少的编码,我的意思是在技术意义上更慢,而不是你真的注意到:“Call”是每个函数的本机javascript方法;检查jQuery内部他是如何做很多事情的,然后在最后使用“apply”(它与“call”类似,但它接受一个数组来创建参数)谢谢。我将使用Andrew的答案,因为它使用更少的编码,我的意思是在技术意义上更慢,而不是你真的注意到:“Call”是每个函数的本机javascript方法;检查jQuery内部他是如何做很多事情的,然后在最后使用“apply”(它与“call”类似,但它接受一个数组来创建参数)