【问题标题】:iterate through html table rows with jquery to get div id inside <td> cells使用 jquery 遍历 html 表行以获取 <td> 单元格内的 div id
【发布时间】:2012-10-02 13:19:30
【问题描述】:

我想遍历表 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>

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

【问题讨论】:

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

标签: javascript jquery html css


【解决方案1】:

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

var dividlist = [];
$("td.theCell div").each(function() {
     dividlist.push(this.id);
});

【讨论】:

    【解决方案2】:

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

    $("#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);
    });​
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        试试这个

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

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

        【讨论】:

        • 如果我有 而不是 怎么办?使用 $("td.theCell foo").each(function() { var id = $(this).find('div').attr('id'); });
        • 那么你的选择器应该是 $("td.theCell.foo") .. 剩下的都是一样的
        【解决方案5】:

        使用find获取后代div:

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

        【讨论】:

          猜你喜欢
          相关资源
          最近更新 更多
          热门标签