[英]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.