2012-01-11 36 views
5

a.nodeName未定義a.nodeName是未定義jQuery的錯誤

我看這件事,但解釋似乎並沒有在所有我清楚。

function deleteThisRow() { 
    $(this).closest('tr').fadeOut(400, function(){ 
     $(this).remove(); 
    }); 
} 
<tr> 
    <td>blah blah blah</td> 
    <td> 
     <img src="/whatever" onClick="deleteThisRow()"> 
    </td> 
</tr> 
+1

裏面'deleteThisRow','this'將把'window',而不是圖像。你爲什麼不把事件處理函數與jQuery綁定? – 2012-01-11 09:48:28

回答

14

在功能並不是指這是點擊的元素this關鍵字。默認情況下,它會引用DOM中的最高元素,即window

試試這個:

<tr> 
    <td>blah blah blah</td> 
    <td><img src="/whatever"></td> 
</tr> 
$("tr td img").click(deleteThisRow); 

function deleteThisRow() { 
    $(this).closest('tr').fadeOut(400, function() { 
     $(this).remove(); 
    }); 
} 
+0

的確,看起來這個錯誤意味着你錯誤地使用了$(this)。在這種情況下,我試圖調用一個函數,我假設它會在特定事件之外被調用。 – neminem 2013-09-12 17:29:11

+1

多年以後,在這樣的情況下,我很快樂地忘了這件事,然後我再次做了同樣的事情,發現了這個非常有用的評論,開始讚揚它,並且不能,結果證明我是寫它的人。謝謝,我自己! :d – neminem 2016-06-10 18:31:47

1

嘗試:

$(document).ready(function() { 
    $("img").click(function() { 
     $(this).closest('tr').fadeOut(400, function(){ 
      $(this).remove(); 
     }); 
    }); 
});