Javascript Jquery动态列表项选择第一个筛选的搜索项
我的问题是,当用户在输入字段上搜索文本时,我如何选择第一个筛选的匹配列表项?如果用户单击,则会自动单击第一个选定项。我将非常感谢你的帮助。提前谢谢Javascript Jquery动态列表项选择第一个筛选的搜索项,javascript,jquery,pug,Javascript,Jquery,Pug,我的问题是,当用户在输入字段上搜索文本时,我如何选择第一个筛选的匹配列表项?如果用户单击,则会自动单击第一个选定项。我将非常感谢你的帮助。提前谢谢 //pug file which displays dynamic list items. Each list item has href tag url link. .row .col-md-8.offset-md-2.pad .form(class="form-row justify-content-center depar
//pug file which displays dynamic list items. Each list item has href tag url link.
.row
.col-md-8.offset-md-2.pad
.form(class="form-row justify-content-center deparrSearchForm")
.form-group.col-md-8
input(type="text" class="form-control form-control-lg" id="fromStation" name="fromStation" placeholder="Type train station name & press enter")
for prop in stationName
ul(class="list-group text-center" id="mylist")
a(href="/train/search-deparrtrain-submit/"+prop.stationShortCode+'/'+prop.stationName)
li(class="list-group-item") #{prop.stationName}
// Jquery which filter my input search text and display list items
$("#fromStation").on("keyup", function() {
var searchText = $(this).val().toLowerCase();
$("#mylist li").filter(function(){
var text= $(this).text().toLowerCase();
if(text.indexOf(searchText) >= 0){
$(this).show();
}
else{
$(this).hide();
}
});
});
我认为您应该在过滤函数中使用
索引
,如:
$("#mylist li").filter(function(index){
var text= $(this).text().toLowerCase();
if(text.indexOf(searchText) >= 0){
$(this).show();
}
else{
$(this).hide();
}
});
然后通过eq
类似于$(this.eq(index)
做任何你想做的事情来找到该元素
或者在过滤函数中使用$(“#mylist”).eq(index)
。我的解决方案:
对于输入字段按键功能,我传递事件,动态列表过滤器功能,我传递索引
在filter函数中,我将过滤列表项的索引值分配给临时数组。我获得所有筛选列表项的位置。现在我可以做任何我想做的事了。对于我的情况,如果用户按enter键,我将显示第一个筛选的列表项
Jquery代码:
$("#fromStation").on("keypress",function(e) {
var searchText = $(this).val().toLowerCase();
var temparr=[];
$("#mylist li").filter(function(index){
var text= $(this).text().toLowerCase();
if(text.indexOf(searchText) >= 0){
$(this).show().first();
temparr.push(index);
}
else{
$(this).hide();
}
});
if(e.which == 13){
$("#mylist li").eq(temparr[0]).click();
console.log(temparr);
return false;
}
})) 对于筛选部分,您可以使用
first()
我试过了,它会选择所有列表项,而不仅仅是第一个筛选项。您可以用完整的代码制作codepen、jsbin或类似的东西吗。@Shekharayal,很高兴听到这个消息,如果您认为这有助于您接受它,请接受它。