我目前正致力于搜索功能,以实时显示结果
问题
我需要将显示的最大结果限制为4
我尝试使用ul.length < 4
,但它无效
默认情况下,显示的li数量为4,搜索时也是4.(稍后将设置为更高的数字)
$("#search_emotions").on("input",function(){
var input, filter, ul, li, a, i;
input = $("#search_emotions");
filter = input.val();
ul = $("#emotions");
ul.find('li').each(function(){
var a = $(this).find("div").text();
if( a.indexOf(filter) > -1) {
$(this).css("display", "");
} else {
$(this).css("display", "none");
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id='search_emotions' placeholder="Search emotions" />
<ul class="emotions" id="emotions">
<li ><div class="emotion_1">A</div></li>
<li ><div class="emotion_2">B</div></li>
<li ><div class="emotion_3">CF</div></li>
<li ><div class="emotion_4">DE</div></li>
<li ><div class="emotion_5">E</div></li>
<li ><div class="emotion_6">FA</div></li>
<li ><div class="emotion_7">GB</div></li>
<li ><div class="emotion_8">H1C</div></li>
<li ><div class="emotion_9">HC2</div></li>
<li ><div class="emotion_10">HC3</div></li>
<li ><div class="emotion_11">HC4</div></li>
<li ><div class="emotion_12">HC5</div></li>
<li ><div class="emotion_13">HC6</div></li>
</ul>
&#13;
答案 0 :(得分:1)
添加一个计数器来计算显示的li数
var limit = 4;
var initialLimit = 5;
$("#search_emotions").on("input",function(){
var input, filter, ul, li, a, i;
input = $("#search_emotions");
filter = input.val();
ul = $("#emotions");
var counter = 0;
var limitNum = filter == "" ? initialLimit : limit;
ul.find('li').each(function(){
var a = $(this).find("div").text();
var condition = counter < limitNum;
if( a.indexOf(filter) > -1 && condition) {
$(this).css("display", "");
counter++;
} else {
$(this).css("display", "none");
}
});
});
$('#search_emotions').trigger('input')
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id='search_emotions' placeholder="Search emotions" />
<ul class="emotions" id="emotions">
<li ><div class="emotion_1">A</div></li>
<li ><div class="emotion_2">B</div></li>
<li ><div class="emotion_3">CF</div></li>
<li ><div class="emotion_4">DE</div></li>
<li ><div class="emotion_5">E</div></li>
<li ><div class="emotion_6">FA</div></li>
<li ><div class="emotion_7">GB</div></li>
<li ><div class="emotion_8">H1C</div></li>
<li ><div class="emotion_9">HC2</div></li>
<li ><div class="emotion_10">HC3</div></li>
<li ><div class="emotion_11">HC4</div></li>
<li ><div class="emotion_12">HC5</div></li>
<li ><div class="emotion_13">HC6</div></li>
</ul>
&#13;