【问题标题】:Jquery dynamic list item select first filtered search itemjquery动态列表项选择第一个过滤的搜索项
【发布时间】:2018-01-15 10:02:35
【问题描述】:

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

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

【问题讨论】:

  • 过滤部分可以使用first()api.jquery.com/first
  • 我试过了,它不仅选择了第一个过滤的列表项。
  • 你能用你的完整代码制作codepen、jsbin或类似的东西吗?

标签: javascript jquery pug


【解决方案1】:

我认为您应该在过滤功能中使用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)

【讨论】:

  • @ShekharAryal,很高兴听到这个消息,如果您认为它对您有帮助,请接受它。
【解决方案2】:

我的解决方案:

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

在过滤器函数中,我将过滤后的列表项的索引值分配给临时数组。我得到了所有过滤后的列表项位置。现在我可以做任何我想做的事了。对于我的情况,如果用户按下回车键,我将显示第一个过滤的列表项。

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;
 }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2014-05-14
    • 1970-01-01
    • 2012-05-21
    • 2016-09-08
    • 2012-03-21
    • 1970-01-01
    相关资源
    最近更新 更多