select2.js外掛支援拼音搜尋(最新版-4.0.6)
阿新 • • 發佈:2018-12-13
通過兩天的研究,學會使用select2.js,並且修改了select2.js的原始碼,實現拼音搜尋的功能(pinyin.js連結,將中文轉換成拼音),下面主要講解如何實現拼音搜尋功能:
1.從https://select2.org/官網上下載最新的select2.js,學習新版本外掛的用法(PS:學習一個新的事物,最好通過官方文件進行了解,這樣獲得的知識是最準確,少走彎路)
2.把select2.js、select2.css拷入自己專案的相應位置
問題一:從github下載的檔案怎麼閱讀,那個資料夾下存放的select2.js和select2.css檔案
github目錄結構說明:
dist 是指編譯後的檔案,可以理解為壓縮釋出版(select2.js和select2.css在那個檔案下
src 原始碼檔案,適合動手能力強的童鞋
docs 文件
examples 示例檔案
test 測試指令碼
.gitignore 告訴git哪些檔案不要上傳到 GitHub,比如資料庫配置檔案等
LICENSE.txt 授權協議
README.md 自述檔案,整個專案的簡介、使用方法等
bower.json Bower 包管理器配置檔案
package.json npm 包管理器配置檔案
3.在select2.js原始碼中進行修改,支援拼音搜尋:
拼音搜尋的原理:
將下拉框選項中的中文轉換成漢語拼音,然後與輸入的字母進行比較,如果包含則被檢索出來。
修改程式碼:
在select2.js中找到matcher 方法,對此方法進行修改。
function matcher (params, data) { // Always return the object if there is nothing to compare if ($.trim(params.term) === '') { return data; } // Do a recursive check for options with children if (data.children && data.children.length > 0) { // Clone the data object if there are children // This is required as we modify the object to remove any non-matches var match = $.extend(true, {}, data); // Check each child of the option for (var c = data.children.length - 1; c >= 0; c--) { var child = data.children[c]; var matches = matcher(params, child); // If there wasn't a match, remove the object in the array if (matches == null) { match.children.splice(c, 1); } } // If any children matched, return the new object if (match.children.length > 0) { return match; } // If there were no matching children, check just the plain object return matcher(params, match); } //支援中文拼音搜尋 2018-09-30 var original = ''; //搜尋輸入的字母 var term = stripDiacritics(params.term).toUpperCase(); if (stripDiacritics(data.text).toPinYin != undefined){ original = stripDiacritics(data.text).toPinYin().toString().indexOf(term); if(original==-1){ //此處是在中文沒有匹配時,匹配對應的拼音 original = stripDiacritics(data.text).toUpperCase().indexOf(term); } } // 修改 if (original> -1) { return data; } // If it doesn't contain the term, don't return anything return null; }
4.實現的Demo(Demo下載連結):