Typeahead 就是那種「你打字打到一半,下面自動跳出候選清單」的元件。Bootstrap 本身有內建一個陽春的版本,但如果想要更接近搜尋引擎的體驗,就得搭配一些外掛與工具函式庫一起用。本文示範如何逐步做到。
UnderScore 官網:https://underscorejs.org/
參考文件:https://www.css88.com/doc/underscore/
<script src="Scripts/bootstrap-typeahead.js"></script> <script src="Scripts/underscore-min.js"></script>
<div style="margin: 10px 50px"> <label for="product_search">Product Search: </label> <input id="product_search" type="text" data-provide="typeahead" data-source='["DATA1", "DATA2", "DATA3"]' /> </div>
只要給 data-provide="typeahead" 與 data-source 兩個屬性,元件就會自動初始化。適合選項固定且不多的情況。
<div style="margin: 10px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search_js" type="text" data-provide="typeahead">
</div>
<script type="text/javascript">
$(document).ready(function ($) {
// 修正一個已知問題:點擊項目後,建議清單不會自動收起來
$.fn.typeahead.Constructor.prototype.blur = function () {
var that = this;
setTimeout(function () {
that.hide()
}, 250);
};
$('#product_search_js').typeahead({
source: function (query, process) {
return ["JS數據1", "JS數據2", "JS數據3"];
},
highlighter: function (item) {
return "==>" + item + "<==";
},
updater: function (item) {
console.log("'" + item + "' selected.");
$("#product_search").val(item);
return item;
}
});
})
</script>
這裡出現了兩個關鍵的覆寫方法:highlighter 決定候選項怎麼被畫出來,updater 決定使用者選中之後要做什麼。把 source 寫成函式,就等於拿到了查詢時機的控制權——這也是下一步能做到 Ajax 的原因。
<div style="margin: 10px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search_ajax" type="text" data-provide="typeahead">
</div>
<script type="text/javascript">
$('#product_search_ajax').typeahead({
source: function (query, process) {
var parameter = { query: query };
$.post('@Url.Action("AjaxService")', parameter, function (data) {
process(data);
});
}
});
</script>
注意 process(data) 這一步:取得資料後必須交給它,候選清單才會更新。query 會是使用者目前輸入的字串,可以直接送到後端做模糊比對。
實務上資料往往不是純字串,而是帶有多個欄位的物件。這時可以借助 UnderScore 的 _.map 把物件陣列投影成字串陣列:
<div style="margin: 10px 50px">
<label for="product_search">Product Search: </label>
<input id="product_search_object" type="text" data-provide="typeahead">
</div>
<script type="text/javascript">
$(function () {
var products = [
{ id: 0, name: "object1", price: 499.98 },
{ id: 1, name: "object2", price: 134.99 },
{ id: 2, name: "object3", price: 49.95 }
];
$('#product_search_object').typeahead({
source: function (query, process) {
// 只取 name 欄位作為顯示與比對的依據
var results = _.map(products, function (product) {
return product.name;
});
process(results);
},
highlighter: function (item) {
return "==>" + item + "<==";
},
updater: function (item) {
console.log("'" + item + "' selected.");
return item;
}
});
});
</script>
</div>
public ActionResult Index() {
return View();
}
public ActionResult AjaxService() {
string query = "";
if (!string.IsNullOrWhiteSpace(Request["Query"])) {
query = Request["Query"].ToString();
}
var data = ("AJAX1,AJAX2,AJAX3").Split(',');
return Json(data);
}
這裡回傳的是 JSON 陣列,前端 process() 拿到的就是它。範例中的 query 並未實際用於篩選,實作時記得補上過濾邏輯,否則不管打什麼都會跳出同一組選項。
效果如下:

以上就是使用 Bootstrap Typeahead 實作搜尋式下拉建議的分享。下一篇會介紹功能更完整的官方 typeahead.js,有興趣的話可以接著看。