首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否获取表中的所有<tr> ID?

是否获取表中的所有<tr> ID?
EN

Stack Overflow用户
提问于 2017-01-13 11:34:37
回答 2查看 10.2K关注 0票数 3

我想获取所有tr id并将其注册到jQuery数组,这是我的表代码:

代码语言:javascript
复制
<div class="table-responsive" style="margin-top: 10px">
    <table class="table table-striped table-bordered" id="tabletmpitem">
        <thead>
        <tr>
            <th>EAN</th>
            <th>Item Name</th>
            <th>Old Price</th>
            <th>New Price</th>
        </tr>
        </thead>
        <tbody id="tbodytmpitem">
            <tr id="1"><td></td>
            <tr id="2"><td></td>
        </tbody>
    </table>
</div>

如何获取所有id并将它们分配给jQuery数组?我想用它来检查表行中存在什么值?所以我想要的是获得所有的tr id并将它们分配给jQuery数组。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-13 11:38:05

迭代tbody中的tr并将其推送到数组中

代码语言:javascript
复制
var arr = [];

$("#tbodytmpitem tr").each(function() {
  arr.push(this.id);
});

console.log(arr);
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table-responsive" style="margin-top: 10px">
  <table class="table table-striped table-bordered" id="tabletmpitem">
    <thead>
      <tr>
        <th>EAN</th>
        <th>Item Name</th>
        <th>Old Price</th>
        <th>New Price</th>
      </tr>
    </thead>
    <tbody id="tbodytmpitem">
      <tr id="1">
        <td></td>
        <tr id="2">
          <td></td>
    </tbody>
  </table>
</div>

票数 9
EN

Stack Overflow用户

发布于 2017-01-13 11:37:19

使用.map()遍历所有tr并返回它们的ID。然后使用$.makeArray()将结果转换为数组。

代码语言:javascript
复制
var array = $.makeArray($('tbody tr[id]').map(function() {
  return this.id;
}));
console.log(array);
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table-responsive" style="margin-top: 10px">
  <table class="table table-striped table-bordered" id="tabletmpitem">
    <thead>
      <tr>
        <th>EAN</th>
        <th>Item Name</th>
        <th>Old Price</th>
        <th>New Price</th>
      </tr>
    </thead>
    <tbody id="tbodytmpitem">
      <tr id="1">
        <td></td>
        <tr id="2">
          <td></td>
    </tbody>
  </table>
</div>

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41626998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档