簡體   English   中英

特定列上的過濾表

[英]Filter table on specific column

我在這里有一個工作示例:

https://plnkr.co/edit/g6geH12xCI8EirNvghsW?p=preview

您會看到,如果在選擇框中選擇“標記”,它將過濾我的表格並同時顯示兩者:

約翰·馬克

馬克·波特

而且我只希望它在第二列上進行過濾...所以只顯示Mark Poet。

我感謝任何有用的提示。

$(document).ready(function ($) {


    $('#mySelector').change(function () {
        var selection = $(this).val();
        $('table')[selection ? 'show' : 'hide']();

        if (selection) {
            $.each($('#myTable tbody tr'), function (index, item) {
                $(item)[$(item).is(':contains(' + selection + ')') ? 'show' : 'hide']();
            });
        }

    });
});

您必須將選擇減少到所需的td,例如這樣

$(item)[$(item).find('td:nth-child(2)').is(':contains('+ selection +')')? 'show' : 'hide']();

注意:在each級別上減少選擇將不起作用,因為您不會隱藏無效行,而是單獨隱藏每個td

工作示例: https : //plnkr.co/edit/yabW9OgQEE5Fb3efF8Q0?p=preview

考慮使用nth-child(n) css選擇器選擇td元素。

例如

td:nth-child(2)

要么

$("#myTable tbody tr td:nth-child(2)")

您可以嘗試$(“#myTable tbody tr td:nth-​​child(2)”)。 這應該工作

假設您總是要在第二列進行過濾,則可以這樣做:

$(document).ready(function($) {
  $('#mySelector').change(function() {
    var selection = $(this).val();
    $('table')[selection ? 'show' : 'hide']();

    if (selection) {
      $('#myTable tbody tr').each(function() {
        var $name = $(this).find("td").first().next();
        var $row = $name.parent();
        if ($name.text() != selection) {
          $row.hide();
        } else {
          $row.show();
        }
      });
    }
  });
});

只需使用td:eq(1) ...定位第二個td ,索引從0開始。

另外, . 符號更易讀,因此我將使用.show().show() .hide()

此外,我不知道為什么要顯示或隱藏表本身,但是,如果不是故意的,則只需在過濾之前顯示所有行即可。 當選擇“請選擇”時,將顯示所有行。 目前,在做出選擇之后再選擇“請選擇”將完全隱藏該表。 因此,您可以使用如下代碼:

https://plnkr.co/edit/M5dyYwiL4ZO9qwnZMMKc?p=preview

 $(document).ready(function($) { $('#mySelector').change(function() { var selection = $(this).val(), row = $('#myTable tbody tr'); row.show(); // show all rows to ensure no row remains hidden if (selection) { // hide the row that doesn't contain selected val td:eq(1) row.filter(function(index, item) { return $(item).find('td:eq(1)').text().indexOf(selection) === -1; }).hide(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <select id='mySelector' class="styled-select slate"> <option value="">Please Select</option> <option value='John'>John</option> <option value='Mark'>Mark</option> <option value='Ace'>Ace</option> </select> <br><br><br> <table id='myTable'> <thead> <tr> <th>ids</th> <th>name</th> <th>address</th> </tr> </thead> <tbody> <tr> <td>1,2</td> <td>John</td> <td>Mark</td> </tr> <tr> <td>3</td> <td>Mark</td> <td>Poet</td> </tr> <tr> <td>2,3</td> <td>Ace</td> <td>Ventura</td> </tr> </tbody> </table> </body> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM