繁体   English   中英

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

[英]Getting parent tr element from child element in jQuery

我的代码中具有以下表结构

<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');
    //...
});

尝试

$(document).ready(function () {
    $('td').click(function(){
        $(this).parent().css("background","red");
    });
});
$('#my-table').on('click', '.edit', function () {
    $(this).closest('tr').css('backgroundColor','red');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM