答案 0 :(得分:0)
因此,正如我在评论中提到的那样,我认为option:containsIgnoreCase
是无效的,因此我制作了自己的过滤器函数,该函数执行的功能几乎相同:
$("#" + id_list + ' option').filter((i, optionElem) => {
// lowercase text coming from each option
let optionText = $(optionElem).text().toLowerCase();
// keep option text if it includes lowercased searched value
return optionText.includes(quoi.toLowerCase());
})
该功能的解释在代码的注释中:)让我知道您是否要解释什么。
我用//$("#" + id_list + ' option:contains("' + quoi + '")')
用您的行替换了该行,结果是:
let found = $("#" + id_list + ' option').filter((i, optionElem) => {
// lowercase text coming from each option
let optionText = $(optionElem).text().toLowerCase();
// keep option text if it includes lowercased searched value
return optionText.includes(quoi.toLowerCase());
})
// next, get first (as you did), select it, and remove 'hidden' class
.filter(':first').prop('selected', true).removeClass('hidden');
如您所见,我将其存储在变量found
中,以便以后可以检查找到了多少个选项,然后从那里决定要做什么。这些检查的外观如下:
// create new blank option -> add any text you want here :)
let blank = $('<option id="blank-option" value="">No matches</option>');
// if input value matched at least 1 option, remove the 'blank' element
if (found.length > 0) {
$("#blank-option").remove();
}
// otherwise, if no matches were found, append the element & make it selected
else {
$("#" + id_list).append(blank);
blank.prop('selected', true);
}
将其全部整合到您的原始功能中:
function filtrer_saisie(quoi, id_list) {
$("#" + id_list + " option").addClass('hidden');
$("#" + id_list + " option").removeProp('selected');
let found = $("#" + id_list + ' option').filter((i, optionElem) => {
// lowercase text coming from each option
let optionText = $(optionElem).text().toLowerCase();
// keep option text if it includes lowercased searched value
return optionText.includes(quoi.toLowerCase());
})
// next, get first (as you did), select it, and remove 'hidden' class
.filter(':first').prop('selected', true).removeClass('hidden');
// create new blank option -> add any text you want here :)
let blank = $('<option id="blank-option" value="">No matches</option>');
// if input value matched at least 1 option, remove the 'blank' element
if (found.length > 0) {
$("#blank-option").remove();
}
// otherwise, if no matches were found, append the element & make it selected
else {
$("#" + id_list).append(blank);
blank.prop('selected', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="rechercher_station" placeholder="Rechercher une station" onkeyup='filtrer_saisie($(this).val(),"staSelect");' />
<select id="staSelect">
<option value="momuproE">MoMuPro</option>
<option value="560">Banteux RD917</option>
<option value="901">Bergues</option>
<option value="554">CD25_1</option>
<option value="555">CD25_2</option>
<option value="556">CD25_3</option>
<option value="557">CD25_4</option>
<option value="558">CD25_5</option>
<option value="559">CD25_6</option>
</select>
P.S。我用这个jsfiddle弄乱了一切,直到一切正常为止-如果需要,可以随意弄乱它。