我想根据按钮中的文本切换表行过滤器

时间:2016-02-25 15:55:13

标签: jquery filter html-table toggle show-hide

<button id="btn">Car</button>
<button id="btn1">Bike</button>
<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>
<script>
$(function () {
    $("#btn").click(function() {
       var type = $(this).text();
        $('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
    });
    $("#btn1").click(function() {
       var type = $(this).text();
        $('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
    });
});
</script>

添加到:Filtering: How to hide/show (toggle) certain table rows on click? 基于Itotally提供的解决方案,我基于按钮文本过滤表行。这是最有效的解决方案吗?

1 个答案:

答案 0 :(得分:2)

还有其他一些解决方案

您可以根据自己的选择添加选择,并仅显示所选项目

在您搜索的td上添加类类型。

Demo

$("#choice").change(function(){
    var choice = $(this).val().toUpperCase();
    $("table tr").each(function (index) {
                if (index !== 0) {
                    $row = $(this);
                    var id = $row.find("td.type").text().toUpperCase();
                    if (id.indexOf(choice) == -1) {
                        $row.hide();
                    }
                    else {
                        $row.show();
                    }
                }
            });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choice">
<option value>All</option>
<option value="Bike">Bike</option>
<option value="Car">Car</option>
</select>

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

如果有很多选择,这可以最大限度地减少按钮数量

您也可以在表格中轻松添加搜索

<强> HTML

<input type="text" name="search" id="search">

<强> Jquery的

$("#search").keyup(function(){
    var search = $(this).val();
    $('td:first-child').parent('tr:not(:contains('+search+'))').toggle();
});