我正在寻找一个预测性搜索框,其执行方式与下面的codpen提供的示例完全相同。
我如何编辑代码,以便不仅仅预测单词' California',我可以预测一个字符串数组?
此外是否可以使单词一旦完成,脚本会尝试预测下一个被输入的单词?
https://codepen.io/sivarp18/pen/ewbmx
$("#search").keyup(function(){
$("#background-input").val('');
var city = "california";
var searchText = $("#search").val();
console.log(searchText.toLowerCase());
if(searchText === "")
$("#background-input").val('');
else if(city.indexOf(searchText.toLowerCase())==0)
{
var currentLength = searchText.length;
$("#background-input").val(searchText+""+city.substring(currentLength));
}
});

#search-div
{
position: relative;
}
#background-input
{
position: absolute;
color: #999999;
height:25px;
width:250px;
}
#search
{
position: relative;
background: transparent;
height:25px;
width:250px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search-div">
<input type="text" id="background-input" />
<input type="text" id="search" placeholder="Type california.." />
</div>
&#13;
答案 0 :(得分:1)
在else / if语句之后,必须在现有代码中实现循环,以循环遍历数组中的每个城市,并在数组中的每个字符串上执行以下代码。
此代码适用于我 -
$("#search").keyup(function(){
$("#background-input").val('');
var cities = ["california", "london", "paris"];
var searchText = $("#search").val();
console.log(searchText.toLowerCase());
if(searchText === "")
$("#background-input").val('');
else {
for(var i = 0; i < cities.length; i++){
if(cities[i].indexOf(searchText.toLowerCase())==0)
{
var currentLength = searchText.length;
$("#background-input").val(searchText+""+cities[i].substring(currentLength));
}
}
}
});