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

前提是你 提交于 2019-12-02 14:41:29
ltotally

$(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.

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.

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