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