[英]How do I chain jquery selectors properly?
我正在尝试使用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>
我有一个与搜索文本框的更改事件关联的函数。 在这个函数中,我基本上想要选择在name或coach列中不包含文本字符串的所有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+'")');
基本上会尝试访问$('#name, #groups')
返回的对象*:contains("foo")
(假设searchValue
为"foo"
$('#name, #groups')
。 我相信我不必说jQuery对象没有这些奇怪名字的属性。
首先,您必须为所有单元格提供一个公共类而不是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
的类添加到它们中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.