获取表中的所有ID?

时间:2017-01-13 03:34:37

标签: javascript jquery html

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

<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数组。

2 个答案:

答案 0 :(得分:8)

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

&#13;
&#13;
<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>
&#13;
module avail
#displayed the openmpi-x86_64 module
module add open-x86_64
which mpirun
#displayed location of mpirun
&#13;
&#13;
&#13;

答案 1 :(得分:3)

使用tr迭代所有$.makeArray()并返回其ID。然后使用var array = $.makeArray($('tbody tr[id]').map(function() { return this.id; })); console.log(array);将结果转换为数组。

&#13;
&#13;
<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>
&#13;
#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    // Complete the code.
    int num1 = 8, num2 = 11;
    for(int n = num1; n <= num2; n++){

        if(n <= 9){
            switch(n){
                case 1: cout << "one\n";
                case 2: cout << "two\n";
                case 3: cout << "three\n";
                case 4: cout << "four\n";
                case 5: cout << "five\n";
                case 6: cout << "six\n";
                case 7: cout << "seven\n";
                case 8: cout << "eight\n";
                case 9: cout << "nine\n";
            }

      }
      else if(n % 2 == 0){ //even
            cout << "even\n";
      }
      else if(n > 9 && n %2 == 1){ //odd
            cout << "odd\n";
      }

   }

    return 0;
}
&#13;
&#13;
&#13;