#javascript #jquery
Вопрос:
У меня есть скрипт с живым фильтром на странице. Как показать сообщение, когда результат пуст? Например, использует мой div.
Мой сценарий:
$("#country_search").keyup(function () {
var filter = $(this).val().trim().toLowerCase();
$('.country-box.search').each(function () {
if ($(this).find("h4").text().toLowerCase().includes(filter)) {
$(this).show();
} else {
$(this).hide();
}
});
});
<div class="error"> No results </div>
Ответ №1:
Вам нужно назначить переменную ( showError
в моем коде), если был найден какой-либо результат.
// default value: show error message
var showError = true;
$("#country_search").keyup(function () {
var filter = $(this).val().trim().toLowerCase();
$('.country-box.search').each(function () {
if ($(this).find("h4").text().toLowerCase().includes(filter)) {
$(this).show();
// result found, don't show error message
showError = false;
} else {
$(this).hide();
}
});
});
if (showError) {
$('.error').show();
}
Комментарии:
1. Не работает. Я всегда вижу сообщение об ошибке
2. Правильно ли это, когда я создаю
var showError = $( ".error" );
Ответ №2:
Это работает на меня
$("#country_search").keyup(function () {
var filter = $(this).val().trim().toLowerCase();
$('.country-box.search').each(function () {
if ($(this).find("h4").text().toLowerCase().includes(filter)) {
$(this).show();
// result found, don't show error message
showError = false;
}
else if($('.country-box.search:visible').length===0){
$('.error').show();
}
else {
$(this).hide();
$('.error').hide();
}
});
});