Filtering: How to hide/show (toggle) certain table rows on click?

為{幸葍}努か 提交于 2019-12-03 01:04:44

问题


Assuming this table (actually it could have more columns and rows):

<table id="vehicles">
  <tr>
    <th>Type</th>
    <th>Color</th>
    <th>Wheels</th>
  </tr>
  <tr>
    <td>Car</td>
    <td>Red</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Blue</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Car</td>
    <td>Blue</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Red</td>
    <td>2</td>
  </tr>
</table>

Now my goal is to be able to click on the table data (cells), for example "Car", and then show only the two cars. Another click on "Car" should show the hole table again. Or one click on "Red", and then only the red vehicles (red car and red motorcycle) should be shown. How can this be achieved using jQuery?


回答1:


$(function () {
    $( "td" ).on( "click", function() {
        var type = $(this).text();
        $('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="vehicles">
  <tr>
    <th>Type</th>
    <th>Color</th>
    <th>Wheels</th>
  </tr>
  <tr>
    <td>Car</td>
    <td>Red</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Blue</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Car</td>
    <td>Blue</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Bike</td>
    <td>Green</td>
    <td>2</td>
  </tr>
  <tr>
    <td>Motorcycle</td>
    <td>Red</td>
    <td>2</td>
  </tr>
</table>

Stores the text from current td, hides tr nodes which do not contain the text.




回答2:


Here's a really really simple test that might help you get started.

    $(function () {
        $("#vehicles tr td").click(function () {
            var desc = $(this).html();
            $("#vehicles tr").css("background-color", "white");
            $("#vehicles").find(":contains(" + desc + ")").closest("tr").css("background-color", "red");
        });
    });

This assigns a click event to every TD element, stores its value somewhere and then checks if said value exists in the table, highlighting the elements that are matched. Give it a spin, I think it'll set you off in the right direction.



来源:https://stackoverflow.com/questions/25730217/filtering-how-to-hide-show-toggle-certain-table-rows-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!