iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 7
3
Modern Web

30天學習30套前端技術(2018年)系列 第 7

[十分鐘學習] typeahead.js - 文字欄位顯示建議列表

example1

由Twitter所推出,靈活紮實的建議列表函式庫

GitHub Star: 14,800
Javascripting Overall: 85%
瀏覽器: ChromeFirefoxIE8+
RWD: 不支援(可運作)
License: MIT


《安裝》

  • CDN

      <!-- jQuery v1.9.1 -->
      <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
      <!-- typeahead.js v0.11.1 -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.jquery.min.js"></script>
    
  • Bower

      $ bower install typeahead.js
    

《範例》

  • 產生建議列表

      <input type="text" class="example" />
      <script>
      	var substringMatcher = function( strs ) {
      		return function findMatches( q, cb ) {
      			var matches, substringRegex;
      			matches = [];
      			substrRegex = new RegExp( q, "i" );
      			$.each( strs, function( i, str ) {
      				if ( substrRegex.test( str ) ) {
      					matches.push( str );
      				}
      			});
      			cb(matches);
      		};
      	var states = [ "Tom", "Mike", "Jack", "Bob" ];
      	$( ".example" ).typeahead({ // 參數設定[註1]
      		highlight: true,  // 標註關鍵字
      		minLength: 1  // 最小關鍵字長度
      	},
      	{
      		name: "states",
      		source: substringMatcher(states) // 建議列表資料
      	});
      </script>
    

    [註1]

    參數 描述

    highlight|標註關鍵字
    minLength|最小關鍵字長度


《延伸》

  1. typeahead.js
  2. twitter/typeahead.js: typeahead.js is a fast and fully-featured autocomplete library

上一篇
[十分鐘學習] Chosen - 下拉式選單全面進化
下一篇
[十分鐘學習] Textillate.js - 絢麗文字動畫特效
系列文
30天學習30套前端技術(2018年)61
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
逮丸逮丸
iT邦大師 1 級 ‧ 2017-12-27 09:44:12

範例沒有作用似的。

mfhsueh iT邦新手 4 級 ‧ 2017-12-27 10:17:00 檢舉

Hi, 為了簡化source,範例只提供兩個關聯詞(Tom、Mike),你可以輸入T或M,就會產生建議列表,謝謝。

我要留言

立即登入留言