8

a.nodeName 未定义

我已经查过了,但解释对我来说似乎并不清楚。

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

3 回答 3

21

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

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

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

function deleteThisRow() {
  $(this).closest('tr').fadeOut(400, function() {
    $(this).remove();
  });
}
img {
  width: 20px;
  height: 20px;
  border: 1px solid #C00;
}
<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>

于 2012-01-11T09:49:47.327 回答
1

尝试:

$(document).ready(function() {
    $("img").click(function() {
        $(this).closest('tr').fadeOut(400, function(){
            $(this).remove();
        });
    });
});
于 2012-01-11T09:50:54.627 回答
1

我遇到了类似的问题,解决方案是从箭头函数切换到传统的命名函数。有时旧是金,但我确信某处有根本原因。

这没有用:

$(document).ready(() => {
  $('#client_id').change(() => {
    const clientId = $(this).val();
    console.log(clientId);
  });
});

控制台打印出错误:

类型错误:i.nodeName 未定义

进一步调查发现,'$(this)' 调用的是 window 对象而不是 select 元素。(正如上面 Rory 所指出的:https ://stackoverflow.com/a/8817193/5925104 )

这行得通。一个值被打印到控制台。

$(document).ready(() => {
  $('#client_id').change(function changeClient() {
    const clientId = $(this).val();
    console.log(clientId);
  });
});

更新

这是箭头函数的局限性之一。我引用,“没有自己的绑定到 this 或 super,不应该用作方法。” 由于上面的 jQuery 方法使用 'this' 上下文,因此在这种情况下应避免使用箭头函数,而应使用传统的函数表达式。这是支持这一点的文档。

于 2019-09-24T19:42:11.077 回答