首页 文章

如何在HTML表上执行实时搜索和过滤

提问于
浏览
119

我一直在谷歌搜索并搜索Stack Overflow一段时间,但我无法解决这个问题 .

我有一个标准的HTML表,包含水果 . 像这样:

<table>
   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

在上面我有一个文本框,我想在表中搜索用户类型 . 因此,如果他们输入 Gre ,表格中的橙色行会消失,留下Apple和Grapes . 如果他们继续并打字 Green Gr 苹果行应该消失,只留下葡萄 . 我希望这很清楚 .

并且,如果用户从文本框中删除了部分或全部查询,我希望现在所有与查询匹配的行重新出现 .

虽然我知道如何删除jQuery中的表行,但我不知道如何根据此选择性地进行搜索和删除行 . 有一个简单的解决方案吗?还是一个插件?

如果有人能指出我正确的方向,它将是辉煌的 .

谢谢 .

8 回答

  • 0

    我创建了这些例子 .

    简单indexOf搜索

    var $rows = $('#table tr');
    $('#search').keyup(function() {
        var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    
        $rows.show().filter(function() {
            var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
            return !~text.indexOf(val);
        }).hide();
    });
    

    Demohttp://jsfiddle.net/7BUmG/2/

    正则表达式搜索

    使用正则表达式的更高级功能将允许您以行中的任何顺序搜索单词 . 如果您键入 apple greengreen apple ,它将工作相同:

    var $rows = $('#table tr');
    $('#search').keyup(function() {
    
        var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
            reg = RegExp(val, 'i'),
            text;
    
        $rows.show().filter(function() {
            text = $(this).text().replace(/\s+/g, ' ');
            return !reg.test(text);
        }).hide();
    });
    

    Demohttp://jsfiddle.net/dfsq/7BUmG/1133/

    去抖动

    当您通过搜索多行和多列实现表过滤时,考虑性能和搜索速度/优化非常重要 . 简单地说你不应该在每次击键时运行搜索功能,这是没有必要的 . 为了防止过滤太频繁,你应该去除它 . 上面的代码示例将变为:

    $('#search').keyup(debounce(function() {
        var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
        // etc...
    }, 300));
    

    你可以选择任何去抖动实现,例如从Lodash _.debounce,或者你可以使用非常简单的东西,就像我在下一个演示中使用的那样(从here去抖动):http://jsfiddle.net/7BUmG/6230/http://jsfiddle.net/7BUmG/6231/ .

  • 2

    我有一个jquery插件 . 它也使用jquery-ui . 你可以在这里看到一个例子http://jsfiddle.net/tugrulorhan/fd8KB/1/

    $("#searchContainer").gridSearch({
                primaryAction: "search",
                scrollDuration: 0,
                searchBarAtBottom: false,
                customScrollHeight: -35,
                visible: {
                    before: true,
                    next: true,
                    filter: true,
                    unfilter: true
                },
                textVisible: {
                    before: true,
                    next: true,
                    filter: true,
                    unfilter: true
                },
                minCount: 2
            });
    
  • 3

    这是在HTML表中搜索的最佳解决方案,同时覆盖 all of the table ,(表中的所有td,tr), pure javascript 和尽可能 short

    <input id='myInput' onkeyup='searchTable()' type='text'>
    
    <table id='myTable'>
       <tr>
          <td>Apple</td>
          <td>Green</td>
       </tr>
       <tr>
          <td>Grapes</td>
          <td>Green</td>
       </tr>
       <tr>
          <td>Orange</td>
          <td>Orange</td>
       </tr>
    </table>
    
    <script>
    function searchTable() {
        var input, filter, found, table, tr, td, i, j;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td");
            for (j = 0; j < td.length; j++) {
                if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                }
            }
            if (found) {
                tr[i].style.display = "";
                found = false;
            } else {
                tr[i].style.display = "none";
            }
        }
    }
    </script>
    
  • 4

    感谢@dfsq提供非常有用的代码!

    我做了一些调整,也许还有一些像他们一样 . 我确保您可以搜索多个单词,而无需严格匹配 .

    示例行:

    • 苹果和梨

    • 苹果和香蕉

    • 苹果和橘子

    • ......

    你可以搜索'ap pe',它会识别第一行
    你可以搜索'banana apple',它会识别第二行

    Demo: http://jsfiddle.net/JeroenSormani/xhpkfwgd/1/

    var $rows = $('#table tr');
    $('#search').keyup(function() {
      var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');
    
      $rows.hide().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        var matchesSearch = true;
        $(val).each(function(index, value) {
          matchesSearch = (!matchesSearch) ? false : ~text.indexOf(value);
        });
        return matchesSearch;
      }).show();
    });
    
  • 0

    我发现dfsq的回答非常有用 . 我做了一些适用于我的小修改(我在这里发布它,以防它对别人有用) .

    • 使用 class 作为挂钩,而不是表元素 tr

    • 在显示/隐藏父项时,在子项 class 内搜索/比较文本

    • 通过将 $rows 文本元素仅存储到数组中一次(并避免 $rows.length 次计算),提高效率

    var $rows = $('.wrapper');
    var rowsTextArray = [];
    
    var i = 0;
    $.each($rows, function() {
      rowsTextArray[i] = $(this).find('.fruit').text().replace(/\s+/g, ' ').toLowerCase();
      i++;
    });
    
    $('#search').keyup(function() {
      var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
      $rows.show().filter(function(index) {
        return (rowsTextArray[index].indexOf(val) === -1);
      }).hide();
    });
    
    span {
      margin-right: 0.2em;
    }
    
    <input type="text" id="search" placeholder="type to search" />
    
    <div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
    <div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
    <div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
    <div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
  • 0

    Datatable JS plugin 也是html表的accomedate搜索功能的一个很好的替代品

    var table = $('#example').DataTable();
    
    // #myInput is a <input type="text"> element
    $('#myInput').on( 'keyup', function () {
        table.search( this.value ).draw();
    } );
    

    https://datatables.net/examples/basic_init/zero_configuration.html

  • 10

    纯Javascript解决方案:

    适用于所有列和不区分大小写:

    function search_table(){
      // Declare variables 
      var input, filter, table, tr, td, i;
      input = document.getElementById("search_field_input");
      filter = input.value.toUpperCase();
      table = document.getElementById("table_id");
      tr = table.getElementsByTagName("tr");
    
      // Loop through all table rows, and hide those who don't match the search query
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td") ; 
        for(j=0 ; j<td.length ; j++)
        {
          let tdata = td[j] ;
          if (tdata) {
            if (tdata.innerHTML.toUpperCase().indexOf(filter) > -1) {
              tr[i].style.display = "";
              break ; 
            } else {
              tr[i].style.display = "none";
            }
          } 
        }
      }
    }
    
  • 280

    你可以使用像这样的原生javascript

    <script>
    function myFunction() {
      var input, filter, table, tr, td, i;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
          if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }       
      }
    }
    </script>
    

相关问题