简体   繁体   English

使用jQuery通过链接过滤表行

[英]Filter table rows by link with jQuery

I searched around and couldn't find an exact solution to my problem, so here goes.我四处搜索,找不到我的问题的确切解决方案,所以这里是。 I'm trying to filter the rows of a table by hiding unmatched rows by link click.我试图通过点击链接隐藏不匹配的行来过滤表的行。

<a class="all">All: 314</a>
<a class="processing">Processing: 16</a>
<a class="completed">Completed: 12</a>
<a class="action">Action Required: 34</a>
<a class="errors">Errors: 6</a>

Here's an abbreviated version of the table:这是该表的缩写版本:

<table id="batch">
<tr class="processing">Processing</tr>
<tr class="completed">Completed</tr>
<tr class="action">Action Required</tr>
<tr class="errors">Error</tr>

Here's the jQuery I'm using (tbody to avoid filtering the thead and some hidden rows):这是我正在使用的 jQuery(tbody 以避免过滤 thead 和一些隐藏的行):

$("a.processing").click(function(){
    $("table#batch tbody tr:not(.processing)").fadeOut();
});

$("a.completed").click(function(){
    $("table#batch tbody tr:not(.completed)").fadeOut();
});

$("a.action").click(function(){
    $("table#batch tbody tr:not(.actionrequired)").fadeOut();
});

$("a.error").click(function(){
    $("table#batch tbody tr:not(.error)").fadeOut();
});

The problem is that once you've filtered by one class, filtering again by another becomes impossible because all of the values except for the ones previously filtered are hidden.问题在于,一旦您通过一个类进行过滤,就不可能再通过另一个类进行过滤,因为除了先前过滤的值之外的所有值都被隐藏了。 This happens with both .fadeOut(); .fadeOut();都会发生这种情况.fadeOut(); and .hide();.hide();

I know there's a much simpler, less hacky way of accomplishing this, I just can't seem to get my head around it or get it to let me filter successively.我知道有一种更简单、更简单的方法来实现这一点,我似乎无法理解它或让它让我连续过滤。

You can use $(this).attr('class') to select tr with same class as clicked a element您可以使用$(this).attr('class')选择tr与同班点击a元素

 $('a').click(function() { $('#batch tr').hide(); $('tr.' + $(this).attr('class') + '').show(); if ($(this).attr('class') == 'all') $('table tr').show(); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="all">All: 314</a> <a class="processing">Processing: 16</a> <a class="completed">Completed: 12</a> <a class="action">Action Required: 34</a> <a class="errors">Errors: 6</a> <br> <table id="batch"> <tr class="processing"> <td>Processing</td></tr> <tr class="processing"> <td>Processing</td></tr> <tr class="processing"> <td>Processing</td></tr> <tr class="completed"> <td>Completed</td></tr> <tr class="completed"> <td>Completed</td></tr> <tr class="action"> <td>Action Required</td></tr> <tr class="errors"> <td>Error</td></tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM