jquery得到所选单选button的父tr
我有以下的HTML
<table id="MwDataList" class="data" width="100%" cellspacing="10px"> .... <td class="centerText" style="height: 56px; "> <input id="selectRadioButton" type="radio" name="selectRadioGroup"></td>
换句话说,我有几行的表,在最后一个单元格中的每一行我有单选button。 我如何获得所选单选button的父行?
我曾经尝试过:
function getSelectedRowGuid() { var row = $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"); var guid = GetRowGuid(row); return guid; }
但是,这个select器似乎是不正确的。
尝试这个。
您不需要在jQueryselect器中通过@作为属性名称的前缀。 使用closest()方法获取与select器匹配的最接近的父元素。
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
你可以像这样简化你的方法
function getSelectedRowGuid() { return GetRowGuid( $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr")); }
closest() – 获取与select器匹配的第一个元素,从当前元素开始,并通过DOM树进行。
作为一个侧面说明,元素的id应该在页面上是唯一的,所以尽量避免在你的标记中看到单选button的id。 如果你不打算使用ID,那就把它从标记中删除。
回答
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
如何find最近的行?
使用.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()– 获取匹配select器的第一个元素 -
.parent()– 获取当前匹配元素集中每个元素的父元素 -
.parents()– 获取当前匹配元素集中每个元素的祖先 -
.children()– 获取匹配元素集中每个元素的子元素 -
.siblings()– 获取匹配元素集中每个元素的同胞 -
.find()– 获取当前匹配元素集中每个元素的后代 -
.next()– 获取匹配元素集中每个元素的紧随其后的同胞 -
.prev()– 获取匹配元素集中每个元素的前一个兄弟元素