我想实现一种类似于jQuery的实时搜索。
但在将输入发送到服务器之前,我希望删除数组中所有长度为3个字符或更少的项(因为在德语中,这些单词通常可以在搜索方面忽略)。
所以 ["this", "is", "a", "test"]
变成了 ["this", "test"]
$(document).ready(function() {
var timer, searchInput;
$('#searchFAQ').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
searchInput = $('#searchFAQ').val().match(/\w+/g);
if(searchInput) {
for (var elem in searchInput) {
if (searchInput[elem].length < 4) {
//remove those entries
searchInput.splice(elem, 1);
}
}
$('#output').text(searchInput);
//ajax call here
}
}, 500);
});
});
现在我的问题是不是所有的项都被移除了,例如我输入 "this is a test","is" 被移除,但 "a" 没有。
JSFIDDLE我认为问题出在 for 循环中,因为如果我用 splice 移除一个项,数组的索引会改变,所以它继续使用“错误”的索引。
也许有人可以帮帮我?