从 jQuery 中的子元素获取父 tr 元素

Getting parent tr element from child element in jQuery

本文关键字:元素 获取 tr jQuery      更新时间:2023-09-26

我的代码中有以下表结构

<tr>
  <td>Text 1 </td>
  <td>Text 2 </td>
  <td> <span class="edit" onclick="EditAccountInfo(id1)" /> </td>
</tr>
<tr>
  <td>Text 1 </td>
  <td>Text 2 </td>
  <td> <span class="edit" onclick="EditAccountInfo(id2)" /> </td>
</tr>

单击<td>中的跨度时,我想突出显示所选行(<tr>)。我在javascript函数中使用以下代码

function EditAccountInfo(id)
{
  $(this).closest('tr').css("background-color", "red");
}

我没有收到任何错误,$(this).closest('tr')返回一个有效的对象,但背景颜色样式未应用于<tr>

我做错了什么?

thiswindow,因为您使用的是内联事件处理程序。我建议采用一种更不引人注目的方法:

<span class="edit" data-account-id="id1" />

$(document).on('click', '.edit', function() {
    var $tr = $(this).closest('tr');
    var id = $(this).data('account-id');
    //...
});
$('#my-table').on('click', '.edit', function () {
    $(this).closest('tr').css('backgroundColor','red');
});

尝试

$(document).ready(function () {
    $('td').click(function(){
        $(this).parent().css("background","red");
    });
});