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

And*_*ich 60 jquery parent jquery-selectors tablerow

我有以下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>
Run Code Online (Sandbox Code Playgroud)

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

我尝试过的:

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

但似乎这个选择器不正确.

Sha*_*oli 155

试试这个.

您不需要@在jQuery选择器中为属性名称添加前缀.使用closest()方法获取与选择器匹配的最接近的父元素.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
Run Code Online (Sandbox Code Playgroud)

您可以像这样简化您的方法

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
Run Code Online (Sandbox Code Playgroud)

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

作为旁注,元素的id应该在页面上是唯一的,所以尽量避免使用相同的单选按钮,我可以在标记中看到.如果您不打算使用ID,则只需将其从标记中删除即可.


Jay*_*tel 53

回答

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
Run Code Online (Sandbox Code Playgroud)

如何找到最近的行?

使用.closest():

var $row = $(this).closest("tr");
Run Code Online (Sandbox Code Playgroud)

使用.parent():

检查此.parent()方法.这是一个替代.prev().next().

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

获取所有表格单元格 <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>
});
Run Code Online (Sandbox Code Playgroud)

查看演示


只获得具体信息 <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>
});
Run Code Online (Sandbox Code Playgroud)

查看演示


有用的方法

  • .closest() - 获取与选择器匹配的第一个元素
  • .parent() - 获取当前匹配元素集中每个元素的父元素
  • .parents() - 获取当前匹配元素集中每个元素的祖先
  • .children() - 获取匹配元素集中每个元素的子元素
  • .siblings() - 获取匹配元素集中每个元素的兄弟姐妹
  • .find() - 获取当前匹配元素集中每个元素的后代
  • .next() - 获得匹配元素集中每个元素的紧随其后的兄弟
  • .prev() - 获取匹配元素集中每个元素的前一个兄弟