我正在尝试使用 jQuery 根据用户输入过滤列表。到目前为止,它工作正常,但如果用户输入多个单词,我希望能够使用相当于 AND 条件的方式充分过滤列表。
例如,如果用户输入“丰田手册”,则仍应显示以下两个元素:
- 丰田 Echo 2001 手册
- 丰田卡罗拉 2006 手册
目前,使用当前的 jsFiddle,过滤器会查找确切的字符串(“丰田手册”),因此找不到。如何修改我的代码以使其按预期工作?
HTML/JS
<label for="filterCars">Filtrer la liste des indicateurs :</label>
<input id="filterCars" class="txtfilterCars" type="text" name="txtRecherche">
<ul class="filterCars">
<li class="elemCar">Ford escort 2001 manual</li>
<li class="elemCar">Ford escort 2002 automatic</li>
<li class="elemCar">Dodge Caravan 2001 automatic</li>
<li class="elemCar">Hyundai Excel 2003 manual</li>
<li class="elemCar">Toyota Echo 2001 manual</li>
<li class="elemCar">Toyota Corolla 2006 manual</li>
<li class="elemCar">Hyundai Accent 2009 Automatic</li>
</ul>
$(document).ready(function () {
function noaccent(myString) {
temp = myString.replace(/[àâä]/g, "a");
temp = temp.replace(/[éèêë]/g, "e");
temp = temp.replace(/[îï]/g, "i");
temp = temp.replace(/[ôö]/g, "o");
temp = temp.replace(/[ùûü]/g, "u");
temp = myString.replace(/[ÀÂÄ]/g, "A");
temp = temp.replace(/[ÉÈÊË]/g, "E");
temp = temp.replace(/[ÎÏ]/g, "I");
temp = temp.replace(/[ÔÖ]/g, "O");
temp = temp.replace(/[ÙÛÜ]/g, "U");
return temp;
}
$("#filterCars").keyup(
function () {
var filter = noaccent($(this).val()),
count = 0;
$(".filterCars li.elemCar").each(
function () {
if (noaccent($(this).text()).search(new RegExp(filter, "i")) < 0) {
$(this).addClass("cacheElementFiltre");
} else if (!($(this).hasClass("cacheElement"))) {
$(this).removeClass("cacheElementFiltre");
count++;
}
});
});
});
CSS
//CSS
.cacheElement, .cacheElementFiltre {
display: none;
}
https://jsfiddle.net/f52o3kpd/ https://jsfiddle.net/f52o3kpd/