簡體   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