单击时隐藏/显示(切换)表格行

时间:2016-03-10 15:45:33

标签: javascript jquery filter html-table toggle

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

跟进:How to hide/show (toggle) certain table rows on click?只要表格元素打开/关闭,这就有效,但如果您在一行中选择一个项目,然后在另一行中选择一个项目,则过滤会搞砸。

1 个答案:

答案 0 :(得分:0)

可能有更好的方法可以做到这一点,但如果您只是跟踪最后点击的类型以及表格是否已经过滤,您可以更清楚何时需要重置表格或应用过滤

https://jsfiddle.net/wilchow/stnnuw0a/1/

$(function () {
        var last_type = null;
    var filtered = false;
    $( "td" ).on( "click", function() {
            console.log("last_type: "+last_type);
        var type = $(this).text();
        console.log("type: "+type);
        if(filtered && last_type == type) {
            // type is already filtered. Show all.
            $("tr, td").show();
          last_type = null; // reset
          filtered = false; // reset
        } else {
            $("tr, td").show(); // show all before filtering
            $('td:first-child').parent('tr:not(:contains('+type+'))').hide();
          filtered = true; // set filter flag to true
        }
        last_type = type; // set last type clicked
    });
});