2017-06-05 124 views
3

我正在爲數組進行搜索。我有一個輸入[文本],例如,我把'禁令',然後我需要所有以'禁令'開頭的結果,例如香蕉,香蕉奶昔,香蕉(油炸)等。針對數組的搜索/過濾器

我會去做這個嗎?我試過了,但每次嘗試都不準確。我試過的是以下。

我有什麼:

var inputBox = document.getElementById('ingredient'); 
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"] 

inputBox.onkeydown = function(evt) { 
     $("#autocomplete").empty(); 

     // INSERT CODE FOR SEARCH FUNCTION 


} 

我有一個非常接近,但是當我輸入「禁令」它想出了「Aardbei」。這顯然是錯誤的。在這裏,也許我忽略了一些東西?

var inputBox = document.getElementById('ingredient'); 
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"]; 

inputBox.onkeydown = function(evt) { 
    $("#autocomplete").empty(); 

    var input, filter, a, i; 
    input = document.getElementById("myInput"); 
    filter = inputBox.value.toUpperCase(); 
    for (i = 0; i < ingredienten.length; i++) { 
     a = ingredienten[i]; 
     if (a.toUpperCase().indexOf(filter) > -1) { 
     //console.log(a); 
     $("#autocomplete").append("<li>" + a + "</li>"); 
     } else { 
     } 
    } 
+0

你需要做一個自動完成? – Kashkain

+1

首先使用onkeyup事件而不是onkeydown。 – Lalit

+1

也許這也有幫助:https://stackoverflow.com/q/29154877/1447675 –

回答

4

我想你應該改用keyup事件,你可以使用正則表達式,並在該filter功能物品排列:

var inputBox = document.getElementById('ingredient'); 
 
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"] 
 

 
inputBox.onkeyup = function(evt) { 
 
    $("#autocomplete").empty(); 
 

 
    var query = $('#ingredient').val(); 
 

 
    // escape regex 
 
    query = query.replace(
 
     /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&" 
 
    ); 
 
    var queryRegExp = new RegExp('^' + query, 'i'); 
 
    
 
    var results = ingredienten.filter(function(item) { 
 
     return queryRegExp.test(item); 
 
    }); 
 
    
 
    results.forEach(function(item) { 
 
     $("#autocomplete").append("<li>" + item + "</li>"); 
 
    }); 
 
    
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input type="text" id="ingredient" /> 
 
<div id="autocomplete"></div>

+0

非常感謝,這是完美的。 –

1

按照說明操作,您可以在數組中使用正則表達式過濾器。

const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case 

這將迭代數組並返回匹配正則表達式的所有結果「以'ban'開始」。

你也可以做一個0-2的子字符串匹配=='禁止',但這是一個更手動。

3

使用jQuery UI autocomplete此任務可以很容易實現:

$('#ingredient').autocomplete({ 
 
    source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"] 
 
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> 
 

 

 

 
<input id="ingredient">