前言
是Bootstrap-3-Typeahead
巡扇,不是Twitter open source
的typeahead
为牍,兩者用法有差異。
外加如果配合原生的Bootstrap3
的話推薦還是用這個(gè)展蒂。
JS文件引用順序
<link rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
簡(jiǎn)單使用
<!-- 通過(guò)data-provide="typeahead"來(lái)聲明這是一個(gè)typeahead組件 -->
<!-- 通過(guò)data-source=來(lái)提供數(shù)據(jù) -->
<input type="text" data-provide="typeahead" autocomplete="off" id="input">
<script type="text/javascript">
$(document).ready(function() {
var dataSource = ['軍工', '高校', '煤化工', '新能源', '節(jié)能環(huán)保', 'AB股', 'AH股', 'HS300'];
$("#input").typeahead({
source: dataSource, // 數(shù)據(jù)源
});
});
</script>
個(gè)性化相關(guān)設(shè)置
<input type="text" data-provide="typeahead" autocomplete="off" id="input">
<script type="text/javascript">
$(document).ready(function() {
var dataSource = ['軍工', '高校', '煤化工', '新能源', '節(jié)能環(huán)保', 'AB股', 'AH股', 'HS300'];
$("#input").typeahead({
source: dataSource, // 數(shù)據(jù)源
items: 8, //最多顯示個(gè)數(shù)
delay: 500, //延遲時(shí)間
//這里一定要return呢簸,否則選中不顯示,外加調(diào)用display的時(shí)候null reference錯(cuò)誤漓概。
updater: function (item) {
return item;
},
//返回選中的字符串
displayText: function (item) {
return item;
},
//選擇項(xiàng)之后的事件漾月,item是當(dāng)前選中的選項(xiàng)
afterSelect: function (item) {
console.log(item);
}
});
});
</script>
ajax動(dòng)態(tài)獲取數(shù)據(jù)
<input type="text" data-provide="typeahead" autocomplete="off" id="input">
<input type="hidden" id="hidden">
<script type="text/javascript">
$(document).ready(function() {
var objects = {};
$("#input").typeahead({
source: function(query, process) { //query是輸入框輸入的文本內(nèi)容, process是一個(gè)回調(diào)函數(shù)
$.post("${base}/demo/list", {name: query}, function(data) {
if (data == "" || data.trim().length == 0) { console.log("沒(méi)有查詢到相關(guān)結(jié)果"); };
var results = [];
for (var i = 0; i < data.length; i++) {
objects[data[i].name] = data[i].id;
results.push(data[i].name);
}
process(results);
});
},
afterSelect: function (item) { //選擇項(xiàng)之后的事件,item是當(dāng)前選中的選項(xiàng)
$("#hidden").val(objects[item]); //為隱藏輸入框賦值
},
});
});
</script>