2013-05-18 38 views
4

我想知道爲什麼$(this)不按我期待的方式工作?在下面的代碼中,當你點擊'刪除圖像'時沒有任何反應。如果您註釋出確認聲明,則當您單擊「刪除圖像」時,背景將變爲綠色。你知道這是爲什麼嗎?看起來$(this)由於確認聲明而指向其他內容。提前致謝!

<a href="#" class='thumbnail the-one delete-file'><i class="icon-remove"></i>Remove Image</a> 

$('.the-one').click(function(){ 
    if(confirm("What do you say?")) { return true;} else {return false;} 
    $(this).css("background", "green"); 

}); 

回答

5

您在設置css之前正在返回,因此該行未被執行。試試:

$('.the-one').click(function(){ 
    if (confirm("What do you say?")) { 
     $(this).css("background", "green"); 
     return true; 
    } else { 
     return false; 
    } 
}); 
+0

謝謝!我的腦子被打了2天 – Tom

5

因爲你有return之前。 return之後的所有內容都不會運行。