jQuery:获取所选单选按钮的父级tr

83

我有以下HTML:

<table id="MwDataList" class="data" width="100%" cellspacing="10px">
    ....

    <td class="centerText" style="height: 56px;">
        <input id="selectRadioButton" type="radio" name="selectRadioGroup">
    </td>

    ....
</table>

换句话说,我有一张只有几行的表格,在每一行的最后一个单元格里都有一个单选按钮。
如何获取所选单选按钮的行?

我尝试过以下方法:

function getSelectedRowGuid() {
    var row = $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr");
    var guid = GetRowGuid(row);
    return guid;
}

但是看起来这个选择器是不正确的。

2个回答

194

试一下这个。

在jQuery选择器中,你不需要使用@前缀来指定属性名称。可以使用closest()方法获取与选择器匹配的最近的父元素。

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
你可以像这样简化你的方法
function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - 获取与选择器匹配的第一个元素,从当前元素开始向上遍历DOM树。

顺便提一下,元素的ID在页面上应该是唯一的,因此尽量避免在标记中为单选按钮设置相同的ID。如果您不打算使用ID,则应将其从标记中删除。


1
抢我的台了。这是 closest() 的文档链接: http://api.jquery.com/closest/ - Dave

74

回答

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

如何找到最近的行?

使用.closest()方法:

var $row = $(this).closest("tr");

使用.parent():

查看这个.parent()方法。它是.prev().next()的替代方法。

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>

获取所有表格单元格 <td>

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});

查看演示


仅获取特定的<td>

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});

查看演示


常用方法

  • .closest() - 获取与选择器匹配的第一个祖先元素
  • .parent() - 获取当前匹配元素集合中每个元素的父元素
  • .parents() - 获取当前匹配元素集合中每个元素的所有祖先元素,直到文档中的根节点
  • .children() - 获取当前匹配元素集合中每个元素的子元素
  • .siblings() - 获取当前匹配元素集合中每个元素的同级元素
  • .find() - 获取当前匹配元素集合中每个元素的后代元素
  • .next() - 获取当前匹配元素集合中每个元素后面紧邻的兄弟元素
  • .prev() - 获取当前匹配元素集合中每个元素前面紧邻的兄弟元素

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接