我已将所有产品名称存储在Array中。我也有一个input [type = text]。我需要一个简单的代码来搜索该数组。SQL命令类似于:(从tbl_product的名称中选择名称,喜欢%txt%的名称]。但是我正在前端实现此功能,并且与后端没有任何连接!
<input type="text" id="mytxt" />
<script>
products_name = ["product one", "product two", ....];
$("#mytxt").keyup(function(){
var txt = $("#mytxt").val();
var results = start_search(txt);// must return an Array
});
function start_search(text){
/// I dont know what to write here
}
</script>
string.includes
可能会帮助
products_name = ["product one", "product two"];
$("#mytxt").keyup(function() {
var txt = $("#mytxt").val();
var results = start_search(txt);
console.log(results);
});
function start_search(text) {
return products_name.filter(pr => pr.includes(text))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mytxt">
如何使用array.indexOf函数?
products_name = ["product one", "product two"];
function start_search(text){
if(products_name.indexOf(text) > -1){
return true;
}else{
return false;
}
};
start_search('product'); // returns false
start_search('product one'); // returns true
start_search('product two'); // returns true
start_search('product three'); // returns false