從這個變化:
setTimeout(hide(this),2000);
這樣:
var self = this;
setTimeout(function() {
hide(self);
},2000);
您立即調用這個函數,它的返回值傳遞給setTimeout
而不是將函數引用傳遞給可以稍後調用的setTimeout
。請記住,(xx)
意味着立即執行。所以hide(this)
意味着現在執行它,而不是更晚。另一方面,function() { hide(this); }
是可以稍後調用的函數引用。
或者,如果你不使用隱藏功能其他地方,那麼你就可以在這樣的整合是:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
var self = this;
setTimeout(function() {
$(self).remove();
},2000);
});
一個有用的語言功能是.bind()
可以使用以「硬連線」this
的值或回調函數的參數值。例如,你可以這樣做:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(function() {
$(this).remove();
}.bind(this),2000);
});
的.bind(this)
套this
當前值是this
值時,調用回調函數。
或者,如果你仍然有功能hide(item)
,那麼你可以使用.bind的參數設置爲hide()
這樣的:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(hide.bind(null, this)), 2000);
});
或者,你可以使用動畫,讓它提供爲您的時機:
$(".addtimer div").click(function(){
$(this).toggleClass("remove").delay(1000).slideUp(1000, function() {
$(this).remove();
});
});
正如你可以看到,有很多的選擇,並且在使用視情況而定了一下,你覺得是什麼讓最清晰的代碼我ñ你的情況和你最舒服的使用方式。
謝謝你,知道有一個更好的辦法 – Skylark 2015-02-07 17:57:35
增加了其他兩個選項的答案。 – jfriend00 2015-02-07 18:04:01
使用var self = this;'因爲他使用的是jQuery,所以我會選擇['.proxy'](http://api.jquery.com/jquery.proxy/)。否則,我會使用'bind'或'closure'(我相信'proxy'用於跨瀏覽器的目的)。 – Xotic750 2015-02-07 18:56:34