我正在尝试使用 jquery 对我的表实现快速搜索/过滤功能。本质上,我想隐藏所有没有我要从要隐藏的搜索框中查找的字符串的行。
我有一个动态创建的表格和一个用作列表过滤器的文本字段。
表:<table id="report-table" class="table">
<thead>
<tr>
<th class="">client</th>
<th class="">coach</th>
<th class="">groups</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">John</td>
<td class="coach">Peter </td>
<td class="groups"> Skiers </td>
</tr>
</tbody>
我有一个与搜索文本框的更改事件相关的函数。在这个函数中,我本质上想选择名称或教练列中不包含文本字符串的所有tr,并向它们添加一个类。我已经尝试了很多东西,但没有得到正确的语法,如何应该这样写吗?
hideSearch: function(e){
console.log("hideSearch called");
var searchValue = this.$el.find('.search-text').val();
if(!searchValue ){
console.log("hideSearch: empty search param");
this.$el.find('tr').removeClass('hidden');
}
else{
console.log("hideSearch: searched for: " + searchValue);
//$('(#name, #groups):contains:not("'+searchValue+'")').parent().addClass('hidden');
var selection =$('#name, #groups').('*:contains("'+searchValue+'")');
console.log(selection);
//console.log($('#name, #groups').('*:contains("'+searchValue+'")'));
//$('(#name, #groups):contains("'+searchValue+'")').parent().addClass('hidden');
//$('#name, #groups').('*:contains:not("'+searchValue+'")').parent().addClass('hidden');
}
最佳答案
$('#name, #groups').('*:contains("'+searchValue+'")');
基本上会尝试访问属性 *:contains
。我相信我不必说 jQuery 对象没有具有如此奇怪名称的属性。$('#name, #groups')< 返回的对象的 ("foo")
(假设 searchValue
是 "foo"
)/
首先,您必须为所有单元格指定一个共同的类,而不是 ID。然后,您应该选择所有行并查看 .name
或 .coach
是否包含搜索值。使用.filter
获取两个单元格都不匹配的单元格:
$('#report-table > tbody > tr').filter(function() {
return $(this).children('.name').text().indexOf(searchValue) === -1 &&
$(this).children('.coach').text().indexOf(searchValue) === -1;
}).addClass('hidden');
如果 .name
单元格和 .coach
单元格均不包含搜索值,则过滤器回调返回 true
。回调返回 true
的行将保留在选择中,并将类 hidden
添加到其中。
关于javascript - 如何正确链接 jquery 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20396428/