在 DOM 层次结构中向上几级到包含表行

Go a few levels up the DOM hierarchy to the containing table row

本文关键字:几级 包含表 层次结构 DOM      更新时间:2023-09-26

我有一个这样的HTML结构:

<tr class = "@rowOrdinal" id = "...">                            
    <td>
        <a href = "#">
            <img src = "/Content/updateIcon.gif" class = "updateResourceImageButton" id = "..." />
        </a>
        &nbsp;
        <a href = "#">
            <img src = "/Content/cancelIcon.gif" class = "cancelImageButton" />
        </a>
        &nbsp;
    </td>
    <td class = "hiddenColumn" id = ...>...</td>
    <td class = "resourceKeyColumn" id = ...>...</td>
    ... and so on...

单击更新链接时,我想获取对该行的引用,即 更新超链接所在的tr元素。

因此,在下面的事件侦听器中,我想将 DOM 层次结构向上提升几个级别。我可以使用简单的JavaScript并使用while循环来获取parentNode,但是我将如何使用jQuery来做到这一点?

function WireHandlers() {
    $('.updateResourceImageButton').click(UpdateResourceLinkClickedHandler);
}
function UpdateResourceLinkClickedHandler() {
  // how do I get a reference to the tr that contains
  // the hyperlink which is the source of this event?
}
$(document).ready(function () { WireHandlers(); });

您正在寻找.closest()方法:

function UpdateResourceLinkClickedHandler() {
    var $tr = $(this).closest('tr');
}
function WireHandlers() {
    $('.updateResourceImageButton').click( function(){
        var trParent = $( this ).parent().parent();
        UpdateResourceLinkClickedHandler();
    });
}

不知道为什么需要父tr引用,所以在我的示例中没有使用它