首页 > 解决方案 > 如何从循环中获取 td 中的值

问题描述

<table data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar">
  <thead>
    <tr>
      <th>Name</th>
      <th>Birthday</th>
      <th>Address</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach($people as $person) { ?>
    <tr>
        <td><?php echo $person["name"]; ?></td>
        <td id="birthday"><?=$person["birthday"] ?></td>
        <td><?php echo $person["address"]; ?></td>
        </tr>
        <?php
        }
        ?>
    </tbody>
</table>

从这张表中,我想从循环中获取生日值。

如何获取 jQuery 中的每个值?

标签: jquery

解决方案


ID 必须是唯一的。让它成为一堂课

$(".birthday").each(function() { // or more specific: $("tbody tr td.birthday")
  console.log($(this).text())
});

// or

$(".birthday").each(function() {
  const bDay = $(this).text() 
  const name = $(this).prev().text();
  console.log(name,bDay)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId"
  data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar">
  <thead>
    <tr>
      <th>Name</th>
      <th>Birthday</th>
      <th>Address</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Fred</td>
      <td class="birthday">25 May 1990</td>
      <td>Road 2</td>
    </tr>
    <tr>
      <td>Joe</td>
      <td class="birthday">5 June 1980</td>
      <td>Road 1</td>
    </tr>

  </tbody>
</table>


推荐阅读