无法从表行中获取兄弟姐妹值

时间:2010-05-24 10:47:18

标签: jquery jquery-selectors

当我点击该行的单选按钮时,我试图从相邻列中获取值。 我能够这样做,但是我面临的问题是,当单选按钮列中有更多元素时,我得到空值(即第二行不起作用)。请帮忙......代码全部如下

<table id="dist_list" class="data">
<tbody>
<tr>
<td>
<input type="radio" value="636406" name="distRG" id="radio_7" /></td>
  <td class="selected">Company 1</td>
  <td class="siteId">1234</td>
  <td class="siteName">First Company Name</td>
</tr>

<!-- Not able to get values from this row, since there are more elements in it -->
<tr>
<td>
<span class="jqTransformRadioWrapper"><a rel="distRG" class="jqTransformRadio" href="#"></a>
<input type="radio" value="636406" name="distRG" id="radio_2" />
</span></td>
  <td class="selected">Company 2</td>
  <td class="siteId">2345</td>
  <td class="siteName">Second Company Name</td>
</tr>

<tr>
<td><input type="radio" value="636406" name="distRG" id="radio_3" /></td>
  <td class="selected">Company 3</td>
  <td class="siteId">3456</td>
  <td class="siteName">Third Company Name</td>
</tr>

<tr>
<td><input type="radio" value="213584" name="distRG" id="radio_4" /></td>
  <td class="selected">Company 4</td>
  <td class="siteId">4567</td>
  <td class="siteName">Fourth Company Name</td>
</tr></tbody></table>

jQuery脚本

$("input[name=distRG]").click(function() {
    var owner = $(this).parent().siblings('td.selected').text();
    var siteId = $(this).parent().siblings('td.siteId').text();
    var siteName = $(this).parent().siblings('td.siteName').text();
    alert(owner);
    alert(siteId);
    alert(siteName);
});

1 个答案:

答案 0 :(得分:1)

第二行中的问题是input不是td的孩子而是span的孩子,因此parent()会给你span和不是td  请改用.closest(),它为您提供与选择器匹配的“最近”祖先:

var owner = $(this).closest('td').siblings('td.selected').text();
var siteId = $(this).closest('td').siblings('td.siteId').text();
var siteName = $(this).closest('td').siblings('td.siteName').text();