【问题标题】:Get data attributes in table all tr获取table all tr​​中的数据属性
【发布时间】:2017-06-12 07:11:32
【问题描述】:

我有这样的表:

  <tr class="alignC even" data-pdp-id="10" role="row"> 
  <tr class="alignC even" data-pdp-id="11" role="row">
  <tr class="alignC even" data-pdp-id="12" role="row"> 
  <tr class="alignC even" data-pdp-id="13" role="row"> 
  <tr class="alignC even" data-pdp-id="14" role="row">

如何使用 jquery 获取包含所有 data-pdp-id 的数组

【问题讨论】:

  • 强烈建议您先自己尝试一下……!否则有 N 种方法可以做到。

标签: jquery html html-table tr


【解决方案1】:

您可以使用 each 循环遍历 tr 元素,在每次迭代中,您可以获得 pdp-id,然后将其推送到预定义的数组中。

var pdpArr = [];
$('.alignC').each(function() {
    pdpArr.push($(this).data('pdp-id'));
});
console.log(pdpArr); // You can get the array of pdp-id at this point

【讨论】:

【解决方案2】:

您可以使用.attr("data-pdp-id").data("pdp-id")

然后,当您拥有数据时,将其推送到 arr。 arr.push($(this).data("pdp-id"))

var arr = []
$("table tr.alignC").click(function() {
  console.log($(this).attr("data-pdp-id"))
})


$("table tr").each(function() {
  arr.push($(this).attr("data-pdp-id"))
})

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="alignC even" data-pdp-id="10" role="row">
    <td>10</td>
  </tr>
  <tr class="alignC even" data-pdp-id="11" role="row">
    <td>11</td>
  </tr>
  <tr class="alignC even" data-pdp-id="12" role="row">
    <td>12</td>
  </tr>
  <tr class="alignC even" data-pdp-id="13" role="row">
    <td>13</td>
  </tr>
  <tr class="alignC even" data-pdp-id="14" role="row">
    <td>14</td>
  </tr>
</table>

【讨论】:

    【解决方案3】:

    您可以使用数据循环并获取该值并将该值推送到数组中。

    var ID=[];
    $('#TableID').find('tr').each(function() {
      ID.push($(this).data('pdp-id'));
    });
    

    【讨论】:

      【解决方案4】:
      var ids=[];
          $('#tableId tr').each(function(){
            ids.push($(this).attr('data-pdp-id'))
          })
      

      检查这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2014-08-06
        • 2016-01-02
        • 1970-01-01
        • 2011-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多