0

我想遍历表 id="myTable" 中每一行中的每个单元格并获取单元格子 div 的 id。

到目前为止,我有类似的东西:

$("td.theCell").each(function() {
  var id = $(this).attr('id'); //this would give me the td id but I want its child div's id
});

我的 html 是这样的:

<table id='myTable'>
  <tr>foo</tr>
  <tr>bar</tr>
    <td>foo</td>
    <td class='theCell'>
      <div id='myDiv'>foo</div>
    </td>
  <tr>foo</tr>
  <tr>bar</tr>
</table>

有人知道这样做的好方法吗?提前致谢。

4

5 回答 5

2

试试这个

$("td.theCell").each(function() {
  var id = $(this).find('div').attr('id'); 
});

您需要正确获取 div 的ID而不是 td.thecell 元素。所以你需要使用.find()来选择里面的潜水..

于 2012-10-11T19:22:24.133 回答
2

将所有 div id 保存在一个数组中。使用.each jsfiddle

var dividlist = [];
$("td.theCell div").each(function() {
     dividlist.push(this.id);
});
于 2012-10-11T19:24:53.737 回答
2

您也可以不使用 find 直接选择子 div:

$("td.theCell div").each(function() {    
      var id = this.id
});​
于 2012-10-11T19:25:12.400 回答
1

使用find获取后代 div :

$("td.theCell").each(function() {
  var id = $(this).find('div').attr('id'); 
});
于 2012-10-11T19:22:23.143 回答
0

您可以通过选择器中的小改动来做到这一点

$("#myTable tr > td.theCell > div").each(function() {//you can remove the '>' if you don't just want the direct children only 
  var k = $(this).attr('id'); 
  console.log(k);
});​
于 2012-10-11T19:28:13.827 回答