选择列Jquery下的所有行

时间:2019-11-14 09:43:49

标签: javascript jquery

单击标题时如何选择列下的所有行?例如说:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>
        Column 1
      </th>
      <th>
        Column 2
      </th>
      <th>
        Column 3
      </th>
    </tr>
  </thead>
  <tbody>
  <tr>
    <td>
    Value 1
    </td>
    <td>
    Value 2
    </td>
    <td>
    Value 3
    </td>
  </tr>
  <tr>
    <td>
    Value 1
    </td>
    <td>
    Value 2
    </td>
    <td>
    Value 3
    </td>
  </tr>
  <tr>
    <td>
    Value 1
    </td>
    <td>
    Value 2
    </td>
    <td>
    Value 3
    </td>
  </tr>
  <tr>
    <td>
    Value 1
    </td>
    <td>
    Value 2
    </td>
    <td>
    Value 3
    </td>
  </tr>
  <tr>
    <td>
    Value 1
    </td>
    <td>
    Value 2
    </td>
    <td>
    Value 3
    </td>
  </tr>
  </tbody>
</table>

我想要实现的是,当我单击Column 1标头时,应选择该列下的所有行,如以下示例所示:

enter image description here

我不太确定如何实现这一目标。如果有人有一个很好的榜样,那将不胜感激!干杯!

1 个答案:

答案 0 :(得分:1)

您可以选择基于标头单元格索引$(elem).index()

$(document).on('click', 'table thead tr th', function() {
  let ind = $(this).index();
  $('table').find('tbody').find('td').removeClass('active')
  $('table').find('tbody').find('tr').each((a,b) => {
    $(b).find('td').eq(ind).addClass('active')
  })
})
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>
        Column 1
      </th>
      <th>
        Column 2
      </th>
      <th>
        Column 3
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Value 1
      </td>
      <td>
        Value 2
      </td>
      <td>
        Value 3
      </td>
    </tr>
    <tr>
      <td>
        Value 1
      </td>
      <td>
        Value 2
      </td>
      <td>
        Value 3
      </td>
    </tr>
    <tr>
      <td>
        Value 1
      </td>
      <td>
        Value 2
      </td>
      <td>
        Value 3
      </td>
    </tr>
    <tr>
      <td>
        Value 1
      </td>
      <td>
        Value 2
      </td>
      <td>
        Value 3
      </td>
    </tr>
    <tr>
      <td>
        Value 1
      </td>
      <td>
        Value 2
      </td>
      <td>
        Value 3
      </td>
    </tr>
  </tbody>
</table>

相关问题