我有一个bootstrap模板,最近我在导航栏的顶部添加了一个文本框。我想在其中搜索某些内容时显示项目的下拉列表,因此它会在键入时自动显示列表。自动显示,无需单击搜索并转到其他页面或任何其他内容。有没有办法做到这一点?
对于那些说“你到目前为止尝试了什么”的人来说,几乎没有什么......因为没有任何东西可以帮助我,所以我花了好几个小时试图得到一个答案并且没有成功。
答案 0 :(得分:1)
您的意思是autocomplete
,例如 TypeAhead ?
https://twitter.github.io/typeahead.js/examples/
如演示所示,您只需使用其类并调用脚本:
<div id="the-basics">
<input class="typeahead" type="text" placeholder="States of USA">
</div>
-
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});