首页 > 解决方案 > 根据表详细信息名称和文本过滤表行

问题描述

jQuery 如何过滤 HTML 表中的行,使用 td 标记中的 name 属性和用户从下拉框中选择的选项值?

这是HTML:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h3>filtering table rows</h3>
<label>filter primary</label>
<select>
  <option></option>
  <option>Watertown</option>
  <option>Rockford</option>
  <option>Springfield</option>
  <option>Evansville</option>
</select>
<table>
  <tr>
    <th>ID</th>
    <th>primary</th>
    <th>secondary</th>
    <th>mode</th>
  </tr>
  <tr>
    <td>101</td>
    <td name="primary">Watertown</td>
    <td name="secondary">Rockford</td>
    <td>bus</td>
  </tr>
  <tr>
    <td>102</td>
    <td name="primary">Springfield</td>
    <td name="secondary">Watertown</td>
    <td>car</td>
  </tr>
  <tr>
    <td>103</td>
    <td name="primary">Evansville</td>
    <td name="secondary">Watertown</td>
    <td>bus</td>
  </tr>
</table>
</body>

这是我到目前为止在 jQuery 上的内容:

// attach event to select box
$('select').on('change', filter);

// filter function
function filter() {
    var selectedOption = $('select').find(':selected').text();

$('td').hide();
$('tr').each(function() {
    $.each(this.cells, function() {
    // need a way to isolate this.cells (td tags) with name attribute equal to "primary" and text within that td tag equal to selectedOption, then hide that table row
  });
});
}

jQuery 还不能工作——我被困在如何隔离所需的行上。

例如,如果用户选择 Watertown 作为主要过滤器,则表格应仅显示 1 行 - 主要列中显示 Watertown 的行。

在此处输入图像描述

标签: jquery

解决方案


您必须根据您选择的值显示表格数据

更新我给<tr id="tableHeading">显示表头

再次更新删除<tr id>并添加tr:first-child代码以显示表头

$('select').on('change', filter);

// filter function
function filter() {
    var selectedOption = $('select').find(':selected').val();
    $('tr').each(function(){
         if($(this).find('td[name=primary]').text() == selectedOption){
            $('tr:first-child').show();
            $(this).show();
         }else{
            $('tr:first-child').show();
            $(this).hide();
         }
      });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option></option>
  <option>Watertown</option>
  <option>Rockford</option>
  <option>Springfield</option>
  <option>Evansville</option>
</select>
<table>
  <tr>
    <th>ID</th>
    <th>primary</th>
    <th>secondary</th>
    <th>mode</th>
  </tr>
  <tr>
    <td>101</td>
    <td name="primary">Watertown</td>
    <td name="secondary">Rockford</td>
    <td>bus</td>
  </tr>
  <tr>
    <td>102</td>
    <td name="primary">Springfield</td>
    <td name="secondary">Watertown</td>
    <td>car</td>
  </tr>
  <tr>
    <td>103</td>
    <td name="primary">Evansville</td>
    <td name="secondary">Watertown</td>
    <td>bus</td>
  </tr>
</table>


推荐阅读