jQuery按列过滤表格行

6
我正在尝试以智能的方式过滤表格行(而不是仅仅依靠大量代码最终完成任务),但缺乏灵感。
我的表格中有5列。在每个列的顶部,都有一个下拉菜单或文本框,用户可以使用它们来过滤表格数据(基本上隐藏不适用的行)。
有很多适用于jQuery的表格过滤插件,但没有一个像这样工作得那么好,这就是复杂的部分:|
5个回答

15

这是一个基本的过滤器示例http://jsfiddle.net/urf6P/3/

它使用jquery选择器 :contains('some text') 和 :not(:contains('some text')) 来决定是否显示或隐藏每一行。这可能会帮助你朝着正确的方向前进。

编辑以包括来自jsfiddle的HTML和javascript:

$(function() {    
    $('#filter1').change(function() { 
        $("#table td.col1:contains('" + $(this).val() + "')").parent().show();
        $("#table td.col1:not(:contains('" + $(this).val() + "'))").parent().hide();
    });

});

这是一种相当高效的方法,但最重要的是,代码非常简洁 :P 谢谢 - Jimbo
非常好的解决方案! - Alphacoder

3
稍微改进Jeff Treuting发布的被接受的解决方案,可以将过滤功能扩展到不区分大小写。我对原始解决方案甚至改进都不做任何功劳。这个改进的想法是从不同SO帖子上发布的解决方案中借鉴来的,由Highway of Life提供。

以下是代码:

// Define a custom selector icontains instead of overriding the existing expression contains
// A global js asset file will be a good place to put this code
$.expr[':'].icontains = function(a, i, m) {
  return $(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

// Now perform the filtering as suggested by @jeff
$(function() {    
    $('#filter1').on('keyup', function() {  // changed 'change' event to 'keyup'. Add a delay if you prefer
        $("#table td.col1:icontains('" + $(this).val() + "')").parent().show();  // Use our new selector icontains
        $("#table td.col1:not(:icontains('" + $(this).val() + "'))").parent().hide();  // Use our new selector icontains
    });

});

1

您可以通过在JQuery过滤器中添加children[column number]来筛选特定列。通常,JQuery会从每行的所有列中查找关键字。如果我们想要仅过滤下表中的ColumnB,则需要像以下脚本中那样添加childern[1]来进行筛选。IndexOf值为-1表示搜索无法匹配。任何大于-1的值都将使整行可见。

ColumnA  |  ColumnB  |  ColumnC
John         Doe         1968
Jane         Doe         1975
Mike         Nike        1990
  $("#myInput").on("change", function () {
     var value = $(this).val().toLowerCase();
     $("#myTable tbody tr").filter(function () {
        $(this).toggle($(this.children[1]).text().toLowerCase().indexOf(value) > -1)              
     });
  });

1

这可能不是最好的方法,而且我也不确定性能如何,但一个选项是为每个列(在每行中)标记一个ID,以列标识符开头,然后是类似于记录标识符的唯一数字。

例如,如果您有一个产品名称列,并且记录ID为763,则我会执行以下操作:

​​<table id="table1">
    <thead>
        <tr>
            <th>Artist</th>
            <th>Album</th>
            <th>Genre</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td id="artist-127">Red Hot Chili Peppers</td>
            <td id="album-195">Californication</td>
            <td id="genre-1">Rock</td>
            <td id="price-195">$8.99</td>
        </tr>
        <tr>
            <td id="artist-59">Santana</td>
            <td id="album-198">Santana Live</td>
            <td id="genre-1">Rock</td>
            <td id="price-198">$8.99</td>
        </tr>
        <tr>
            <td id="artist-120">Pink Floyd</td>
            <td id="album-183">Dark Side Of The Moon</td>
            <td id="genre-1">Rock</td>
            <td id="price-183">$8.99</td>
        </tr>
    </tbody>
</table>

然后您可以使用jQuery根据id的开头进行过滤。

例如,如果您想按艺术家列进行过滤:

var regex = /Hot/;
$('#table1').find('tbody').find('[id^=artist]').each(function() {
    if (!regex.test(this.innerHTML)) {
        this.parentNode.style.backgroundColor = '#ff0000';
    }
});

如果仅按ID搜索不够,如果我想要在每一行的每一列中进行搜索呢? - Si8

0

步骤1:在 .html 文件中编写以下内容

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
</table>

步骤2:在.js文件中编写以下内容

function myFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  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")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接