2012-01-09 88 views
1

我有一個contenteditable股利,當你鍵入它,2秒後,我嘗試改變它的背景顏色。當在輸入中輸入X秒後改變背景顏色

這是我的代碼:

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) 
    }); 

看來,我必須通過$(本)的功能,因爲它不承認這$這是。

當我在按鍵功能中設置背景顏色更改時,它會起作用。

的jsfiddle:http://jsfiddle.net/uc8Tg/

回答

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); 
}); 

實施例:http://jsfiddle.net/uc8Tg/1/

+0

非常感謝。我再一次從你身上學到了一些新東西。 – jQuerybeast 2012-01-09 01:00:50

+0

@jQuerybeast:很高興爲您提供幫助! – 2012-01-09 01:01:39

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

+0

謝謝。我將使用安德魯的答案,因爲它使用較少的編碼 – jQuerybeast 2012-01-09 01:02:28

+0

但它更慢 – 2012-01-09 01:44:12

+0

它真的慢嗎? – jQuerybeast 2012-01-09 08:18:18