我正在使用 jQuery 在頁面上的 html 中進行“實時”文本搜索。
當至少輸入三個字符以開始搜索時,以下功能可用作“實時”搜索。
$('#search').keyup(function() {
var text = $(this).val().trim();
var minLength = 2;
$('.record.active').removeClass("active");
if (!text.length) return;
if (text.length > minLength)
$('.record').each(function() {
if ($(this).text().toLowerCase().includes(text)) {
$(this).addClass("active");
}
});
但我想做的是在沒有結果時顯示“無結果”。我正在嘗試使用 if else 陳述句來確定活動類是否有任何記錄。但是下面的代碼片段中的功能不起作用;它只是顯示“沒有結果沒有結果沒有結果沒有結果......”沒有搜索結果。
$('#search').keyup(function() {
var text = $(this).val().trim();
var minLength = 2;
$('.record.active').removeClass("active");
if (!text.length) return;
if (text.length > minLength)
$('.record').each(function() {
if ($(this).text().toLowerCase().includes(text))
$(this).addClass("active");
else
$('.record').not("active");
$(".no-results").append("No Results");
});
});
.record {
display: none;
}
.record.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Search <input type='text' id='search' placeholder='Search Text'>
<br />
<div class="no-results"></div>
<br />
<div class="record">Now is the time for all good men to come to the aid of their city</div>
<div class="record">Now is the time for all good women to come to the aid of their country</div>
<div class="record">Now is the time for all droids to come to the aid of their universe</div>
<div class="record">Now is the time for all fluffy bears to come to the aid of their wilderness</div>
<div class="record">Now is the time for all short people to come to the aid of their county</div>
uj5u.com熱心網友回復:
您應該在if陳述句周圍使用花括號來提高代碼可讀性。
要處理沒有結果的情況,您可以div根據具有active類的記錄數顯示/隱藏 a :
$('#search').keyup(function() {
var text = $(this).val().trim();
var minLength = 2;
$('.record.active').removeClass("active");
if (!text.length) return;
if (text.length > minLength)
$('.record').each(function() {
if ($(this).text().toLowerCase().includes(text)) {
$(this).addClass("active");
}
if($('.record.active').length){
$(".no-results").hide();
} else {
$(".no-results").show();
}
});
});
.record {
display: none;
}
.record.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Search <input type='text' id='search' placeholder='Search Text'>
<br />
<div class="no-results">No results</div>
<br />
<div class="record">Now is the time for all good men to come to the aid of their city</div>
<div class="record">Now is the time for all good women to come to the aid of their country</div>
<div class="record">Now is the time for all droids to come to the aid of their universe</div>
<div class="record">Now is the time for all fluffy bears to come to the aid of their wilderness</div>
<div class="record">Now is the time for all short people to come to the aid of their county</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396442.html
標籤:javascript 查询
