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

后端 未结 2 839
野性不改
野性不改 2021-01-29 12:07

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

Type Color&
相关标签:
2条回答
  • 2021-01-29 12:47

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

    0 讨论(0)
  • 2021-01-29 12:48

    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.

    0 讨论(0)
提交回复
热议问题