如何在动态点击TR列中获取TR的第二个TD

how to get second td for tr in dynamic click tr column

本文关键字:TR 获取 第二个 TD 动态      更新时间:2023-09-26

如何获取第二个TD文本值。当我单击任何TR列时,必须显示到第二个TD文本值

td:hover{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table border="1px">
  <thead>
    <tr>
      <th>row1</th><th>row2</th><th>row3</th><th>row4</th><th>row5</th>
    </tr>
  </thead>
  <tbody>
    <tr data-class="weeks">
      <td class="cls">1</td><td class="cls">2</td><td>3</td><td>4</td><td>5</td>
    </tr>
    <tr data-class="weeks">
      <td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
    </tr>
  </tbody>
</table>

$('td').click(function(){//add click event on each td
  console.log($(this).closest('tr').find('td:nth-child(2)').text());//log the result of getting the second td text
})
td:hover{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table border="1px">
  <thead>
    <tr>
      <th>row1</th><th>row2</th><th>row3</th><th>row4</th><th>row5</th>
    </tr>
  </thead>
  <tbody>
    <tr data-class="weeks">
      <td class="cls">1</td><td class="cls">2</td><td>3</td><td>4</td><td>5</td>
    </tr>
    <tr data-class="weeks">
      <td>6</td><td>7</td><td>8</td><td>9</td><td>10</td>
    </tr>
  </tbody>
</table>

$(this).closest('tr').find('td:nth-child(2)').text()
  1. 使用 .closest('tr') 获取点击的 td 的行
  2. 使用 .find('td:nth-child(2)')获取单击行的第二个 td
  3. 使用 .text()获取单击行的第二个 td 的文本