【发布时间】:2015-05-22 04:16:07
【问题描述】:
我有一个过滤器函数,它需要根据输入字段的值检查元素数组。我最初使用 this solution,但当输入第二个或第三个词时,它会重新评估所有结果。
这是我的情况Fiddle。
目前,如果我输入“鱼”,它将只返回包含“鱼”的行,到目前为止一切顺利。如果我还输入'yellow',所以'fish yellow',它返回'Fish'和'Parrot',而我实际上希望它仍然只返回'Fish',因为它是唯一包含所有术语的行 在输入字段中。
所以不要像这样过滤:
input value = "Term1 Term2 Term3"
- Term1,重新开始,然后
- Term2,重新开始,然后
- 第三学期,重新开始……
有没有办法像这样过滤“jo”数组:
- Term1,然后
- Term1 和 Term2,然后
- Term1 和 Term2 和 Term3 等等?
下面,我尝试将输入字段中的单词数推入另一个数组,然后尝试让它依次循环遍历所有单词,但它不起作用:(
HTML
<input id="filter-field" placeholder="Search" type="text" />
<table cellspacing="0" cellpadding="0" >
<thead>
<tr>
<th>Pet</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>cat</td>
<td>white</td>
</tr>
<tr>
<td>dog</td>
<td>black</td>
</tr>
<tr>
<td>parrot</td>
<td>yellow</td>
</tr>
<tr>
<td>fish</td>
<td>yellow</td>
</tr>
<tr>
<td>hamster</td>
<td>black</td>
</tr>
</tbody>
</table>
jQuery
$("#filter-field").on('input', function() {
// Split the current value of searchInput
var data = this.value.split(" "),
inputLength = $("#filter-field").val().length;
// Create a jquery object of the rows
var jo = $("table > tbody").find("tr");
if (this.value == "") {
jo.show();
return;
}
// Hide all the rows
jo.hide();
jo.filter(function() {
var $t = $(this),
textField = $('#filter-field').val().split(" "),
wordCount = textField.length - 1, // Get length of array, then subtract 1 so 'word #1' matches 'position 0' in array
wordCounter = [];
// I wanted this to end up as [1, 2, 3, 4 etc] to somehow check each word against 'jo', but each .push() simply adds 1 to the first array value
wordCounter.push(wordCount);
// I want this to check for 'word A', then if I enter further words, 'word A and word B' etc
if ($t.is(":contains('" + textField[wordCounter] + "')")) {
return true;
} else {
return false;
}
}).show();
});
【问题讨论】:
-
在 "Term1 and Term2 and Term3 etc?" 是否要求显示所有“Term1 and Term2 and Term3 etc?” ?
-
是的,要求是只显示包含所有术语的结果,而不仅仅是输入的最后一个
-
显示整个
tr,还是只显示包含匹配项的td?td最初是隐藏的吗?
标签: javascript jquery loops filter