【问题标题】:Hide/show (toggle) table rows on click单击时隐藏/显示(切换)表格行
【发布时间】:2016-12-26 18:39:04
【问题描述】:
$(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? 只要打开/关闭表格元素,此功能就可以工作,但如果您在一行中选择一个项目,然后在另一行中选择一个项目,过滤就会混乱。

【问题讨论】:

  • 那么,你的问题是什么?

标签: javascript jquery filter html-table toggle


【解决方案1】:

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

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
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2019-06-14
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多