2017-03-19 50 views
0

我無法弄清$("identifier").remove如何與setTimeout()配合使用。下面的代碼試圖動畫雪花落下jQuery setTimeout()回調不起作用

//construct a html string 
    var html_str = "<img class='snowflakes' src = 'snowflake1.png' style='position: absolute; left: " + String(pos_x) + "px'> " 

    //Append the element to field 
    var flake = $(html_str).appendTo('#field'); 

    flake.animate({top: String(FIELD_SIZE-FLAKE_SIZE)+'px'}, 
        drop_speed, 

        //callback function when finished animating 
        function(){ 
         setTimeout(function(){flake.remove();},1000); 
        } 
    ); 

我不明白它是如何

setTimeout(function(){flake.remove();},1000); //this works 
    setTimeout(flake.remove,1000); //but this doesn't remove the element 

在我看來,兩者都應該執行相同的功能。這裏發生了什麼?

+2

兩個呼叫同一'一個.remove()'函數,但是在函數內有'this'的不同值。 – nnnnnn

回答

3

第二個沒有工作,因爲它是在全球範圍內執行的。下面是關於傳遞給setTimeout的功能的情況下this的文章,按照MDN (Check 'The "this" problem)'

你的代碼,如果這樣寫,將工作:

setTimeout(flake.remove.bind(flake),1000);