我有一个过滤器函数,需要根据输入字段的值检查元素数组。我最初使用 this solution ,但当输入第二个或第三个术语时,它会重新评估所有结果。
这是一个 Fiddle 我的情况。
目前,如果我输入“fish”,它只会返回包含“fish”的行,到目前为止一切顺利。如果我还输入“黄色”,即“鱼黄”,它会返回“鱼”和“鹦鹉”,而我实际上希望它仍然只返回“鱼”,因为它是包含所有术语的唯一行 在输入字段中。
所以不要像这样过滤:
输入值 =“Term1 Term2 Term3”
- 第 1 学期,重新开始,然后
- 第二学期,重新开始,然后
- 第三学期,重新开始...
有没有办法像这样过滤“jo”数组:
- 第 1 学期,然后
- 第 1 学期和第 2 学期,然后
- 第 1 学期、第 2 学期和第 3 学期等?
下面,我尝试将输入字段中的单词数插入另一个数组,然后尝试让它按顺序循环遍历所有单词,但它不起作用:(
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();
});
最佳答案
您解决问题的方式看起来很尴尬。我认为这样的事情应该可以正常工作:
jo.filter(function() {
var $t = $(this),
textField = $('#filter-field').val().split(" ");
for(var i=0; i<textField.length; i++)
{
if (!$t.is(":contains('" + textField[i] + "')"))
{
return false;
}
}
return true;
}).show();
关于javascript - 使用javascript顺序循环遍历一个数组和另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29137992/