繁体   English   中英

jQuery动态列表项选择第一个过滤的搜索项

[英]Jquery dynamic list item select first filtered search item

我的问题是,当用户在输入字段上搜索文本时,如何选择第一个过滤的匹配列表项? 如果用户单击输入,它将自动单击第一个选定的项目。 我将非常感谢您的帮助。 提前致谢。

//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();
    }    
 });
});

我认为您应该在过滤器功能中使用index ,例如:

 $("#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)

我的解决方案:

对于输入字段按键功能,我传递事件,对于动态列表过滤器功能,我传递索引。

在过滤器功能中,我将过滤后的列表项的索引值分配给临时数组。 我得到所有过滤列表项的位置。 现在我可以做任何我想做的事。 就我而言,如果用户按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;
 }

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM