a.nodeName未定义Jquery错误

Bar*_*ney 7 javascript jquery nodename

a.nodeName未定义

我看了这个,但解释似乎对我来说都不清楚.

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

Ror*_*san 20

this函数中的关键字不引用被单击的元素.默认情况下,它将引用DOM中的最高元素,即window.

要解决此问题,您可以使用不显眼的事件处理程序,而不是过时的on*事件属性,因为它们在引发事件的元素范围内运行.试试这个:

$("tr td img").click(deleteThisRow);

function deleteThisRow() {
  $(this).closest('tr').fadeOut(400, function() {
    $(this).remove();
  });
}
Run Code Online (Sandbox Code Playgroud)
img {
  width: 20px;
  height: 20px;
  border: 1px solid #C00;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>blah blah blah 1</td>
    <td><img src="/whatever"></td>
  </tr>
  <tr>
    <td>blah blah blah 2</td>
    <td><img src="/whatever"></td>
  </tr>
  <tr>
    <td>blah blah blah 3</td>
    <td><img src="/whatever"></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)