好程式就是讓人用得順手的程式。前陣子研究了一下如何用 jQuery 模仿百度、Google 那種邊打字邊補全搜尋結果的提示效果,做出來還挺有成就感,特別整理出來跟大家分享。這裡會用到 autocomplete 外掛,請看以下程式碼。
<script type="text/javascript">
$().ready( function () {
$(":text").result(auto);
function auto(data){
$("#keyWord").val(data.name);
}
$("#keyWord").autocomplete(obj, {//obj 是資料物件陣列(Json)
minChars: 0, // 自動完成啟動前需填入的最小字元數
max: 5, // 清單顯示的條目數
autoFill: true, // 是否自動填入
mustMatch: false, // 輸入內容必須符合條目,否則清空
matchContains: true, // 包含比對,相當於模糊比對
scrollHeight: 200, // 清單顯示高度,預設 180
formatItem: function (row) { return row.name; },
formatMatch: function (row) { return row.name; },
formatResult: function (row) { return row.value; }
});
});
</script>
<div>
<h4> 模仿 BaiDu、google 搜尋提示功能</h4>
<table>
<tr><td>名稱:<input type="text" id="keyWord" /></td></tr>
</table>
</div>
其中 obj 是後端傳來的 JSON 資料陣列,透過 formatItem、formatMatch、formatResult 這幾個回呼函式,就能自訂提示文字的比對與顯示方式,做出接近搜尋引擎的下拉體驗。