假设我们有以下 html 表(包含 Product、category 和 Customer 列)
<input type="text" id="order_search" value="" />
<table border="1" padding="5" width="100%">
<thead>
<tr>
<th>Product</th>
<th>Category</th>
<th>Customer</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bananas</td>
<td>fruits</td>
<td>Al pacino</td>
</tr>
<tr>
<td>Pork</td>
<td>Meat</td>
<td>Nick the americans</td>
</tr>
<tr>
<td>Juice</td>
<td>Beverages</td>
<td>The kingo</td>
</tr>
<tr>
<td>Nike SB</td>
<td>Shoes</td>
<td>Nike</td>
</tr>
</tbody>
我们将创建函数来为每一行创建和分配一个唯一的 data-id,以便我们可以更轻松地引用
var uniqueId = 0;
function createUniqueId(){
return ++uniqueId+'_tr';
}
循环所有 tbody>tr 并分配一个唯一的 data-id
$('table tbody tr').each(function(index,tr){
$(tr).attr('data-id',createUniqueId());
});
在#order_search 元素的每个键位上,我们:
抓住价值
清除所有多余的空格
用空格分割并为每个单词创建一个数组
循环这个数组,在这个数组里面循环每一行,在每一行循环每一列(就像你之前做的那样)
如果我们有匹配,则将此行(而不是未找到匹配)保存在 rows_found 数组中
6.循环所有行并将不在rows_found数组中的行隐藏
$("#order_search").keyup(function () {
//In every keyup restore all rows
$("table tbody tr").each(function(index, tr){
$(tr).css({'display':'table-row'})
});
var value = $(this).val().toLowerCase().trim();
//remove extra spaces
value = value.replace(/\s+/g,' ');
//Split the search field value by ' ' space and create an array which we will loop
var value_ar = value.split(' ');
var rows_found = [];
for(var v=0;v<value_ar.length;v++){
var cvalue = value_ar[v];
$("table tbody tr").each(function (index,tr) {
$(tr).find("td").each(function (indextd, td) {
var id = $(td).text().toLowerCase().trim();
var found = (id.indexOf(cvalue) != -1)?true:false;
if(found){
//save a reference of all tr data-ids that found a match
rows_found.push($(this).parent().attr('data-id'));
}
});
});
}//end for
//Loop of rows and hide the one that were not found
$("table tbody tr").each(function(index, tr){
var myid = $(tr).attr('data-id');
if($.inArray(myid,rows_found)<0){
$(tr).css({'display':'none'});
}
});
});