select2 api参数的文档
select2 api參數的文檔
| 具體參數可以參考一下: 參數 | ? 類型 | ? 描述 |
| Width | 字符串 | 控制?寬度?樣式屬性的Select2容器div |
| minimumInputLength | int | 最小數量的字符 |
| maximumInputLength | int | 最大數量的字符 |
| minimumResultsForSearch | Int | 最小數量的結果 |
| maximumSelectionSize | int | 可選擇的最大條目數 |
| placeholder | 字符串 | 選擇初始值 |
| separator | 字符串 | 分隔符字符或字符串用來劃定id |
| allowClear | 布爾 | 此選項只指定占位符 |
| multiple | 布爾 | Select2是否允許選擇多個值 |
| openOnEnter | ? | 打開下拉如果設置為true,當用戶按下回車鍵,Select2關閉。?默認情況下啟用這個選項。 |
| id | 函數 | 函數用于獲取id從選擇對象或字符串id存儲代表的關鍵 |
| matcher | 函數 | 用于確定是否搜索詞匹配一個選項時使用一個內置的查詢功能 |
| sortResults | 函數 | 用于排序列表搜索之前顯示的結果。 |
| formatSelection | 函數 | 函數用于呈現當前的選擇 |
| formatResult | 函數 | 函數用來渲染結果, |
| formatResultCssClass | 函數 | 函數用于添加css類結果元素 |
| formatNoMatches | 字符串/函數 | 字符串包含“不匹配”消息,或? |
| formatSearching | 字符串/函數 | 字符串包含“搜索…?“消息,或? |
| formatAjaxError | 字符串/函數 | 字符串包含消息“加載失敗”,或? |
| formatInputTooShort | 字符串/函數 | 包含“搜索”輸入太短消息的字符串,或? |
| formatInputTooLong | 字符串/函數 | 包含“搜索”輸入太短消息的字符串,或? |
| formatInputTooLong | 字符串/函數 | 包含“搜索輸入字符串太長”消息,或? |
| formatSelectionTooBig | 字符串/函數 | 字符串包含“你不能選擇任何更多的選擇”消息,或? |
| formatLoadMore | 字符串/函數 | 字符串/函數 |
| createSearchChoice | 函數 | 創建一個新的可選選擇從用戶的搜索詞。?允許創建通過查詢選擇不可用?功能。?有用的用戶可以創建動態的選擇時,如“標簽”usecase。 |
| createSearchChoicePosition | 函數/字符串 | 定義的位置插入元素 |
| initSelection | 函數 | 調用Select2創建允許用戶初始化選擇的值?select2附加到元素 |
| tokenizer | 函數 | 記號賦予器函數可以處理后輸入搜索框的輸入每一個按鍵和提取?并選擇選擇。 |
| tokenSeparators | 函數 | 一個字符串數組定義標記為默認的分隔符?分詞器?功能。?默認情況下,此選項設置為一個空數組標記這意味著使用默認?編譯器是禁用的。?通常是明智的,設置該選項值相似?[',','?']?。 |
| query | 函數 | 函數用于搜索詞的查詢結果。 |
| ajax | 對象 | 選擇內置的ajax查詢功能。?這個對象作為快捷方式有手動編寫一個函數,執行ajax請求。?內置函數支持更高級的特性,比如節流和無序的反應。 |
| data | 數組/對象 | 擇建在查詢功能,使用數組。 |
| tags | 數組/函數 | 將Select2放入“標簽'mode,用戶可以添加新的選擇和預先存在的標簽是通過提供?這個選項的屬性是一個?數組?或者一個?函數?返回一個?數組的?對象?或?字符串?。?如果?字符串?而不是使用?對象?他們將有一個被轉換成一個對象?id?和?文本?屬性相等?的值?字符串?。 |
| containerCss | 函數/對象 | 內聯css將被添加到select2的容器。?一個對象包含css屬性/值密鑰對或一個函數,這個函數返回一個對象。 |
| containerCssClass | 函數/字符串 | Css類將被添加到select2容器的標簽。 |
| dropdownCss | 函數/對象 | 內聯css將被添加到select2下拉的容器。?一個對象包含css屬性/值密鑰對或一個函數,這個函數返回一個對象。 |
| dropdownCssClass | 函數/字符串 | Css類將被添加到select2下拉的容器。 |
| dropdownAutoWidth | 布爾 | 當設置為?真正的?嘗試自動尺寸下拉基于內容的寬度。 |
| adaptContainerCssClass | 函數 | 過濾器/重命名的css類,因為他們被復制從源標簽select2容器標簽 |
| adaptDropdownCssClass | 函數 | 濾器/重命名的css類,因為他們被復制從源標簽select2拉標簽 |
| escapeMarkup | 函數 | 函數用于后處理標記從格式化程序返回功能。?默認情況下這個功能轉義的html實體,以防止javascript注入。 |
| selectOnBlur | 布爾 | 設置為?真正的?如果你想要Select2選擇當前高亮選項時模糊。 |
| loadMorePadding | 整數 | 定義了多少像素需要加載下一頁前折以下。?默認值是?0?這意味著結果列表需要滾動到下一個頁面的底部加載的結果。?這個選項可以用來觸發加載更快,可能導致更流暢的用戶體驗。 |
| nextSearchTerm | 函數 | 函數用于確定下一個搜索詞應該是什么 |
??
Example Code(針對目標元素為 div 例如:<div id="e1">...</div> )
function?log(e)?{ var?e=$("<li>"+e+"</li>"); $("#events_11").append(e); e.animate({opacity:1},?10000,?'linear',?function()?{?e.animate({opacity:0},?2000,?'linear',?function()?{e.remove();?});?}); } // 對元素 進行事件注冊 $("#e11")
.on("change",?function(e)?{?log("change "+JSON.stringify({val:e.val,?added:e.added,?removed:e.removed}));?}) ?// 改變事件
.on("select2-opening",?function()?{?log("opening");?}) ?// select2 打開中事件
.on("select2-open",?function()?{?log("open");?}) ? ? // select2 打開事件
.on("select2-close",?function()?{?log("close");?}) ?// select2 關閉事件
.on("select2-highlight",?function(e)?{?log?("highlighted val="+?e.val+" choice="+?JSON.stringify(e.choice));}) ?// 高亮
.on("select2-selecting",?function(e)?{?log?("selecting val="+?e.val+" choice="+?JSON.stringify(e.choice));}) ?// 選中事件
.on("select2-removing",?function(e)?{?log?("removing val="+?e.val+" choice="+?JSON.stringify(e.choice));}) ?// 移除中事件
.on("select2-removed",?function(e)?{?log?("removed val="+?e.val+" choice="+?JSON.stringify(e.choice));}) ?// 移除完畢事件
.on("select2-loaded",?function(e)?{?log?("loaded (data property omitted for brevity)");}) ?// 加載中事件
.on("select2-focus",?function(e)?{?log?("focus");}) ? ?// ?獲得焦點事件
.on("select2-blur",?function(e)?{?log?("blur");}); ? ? // ?失去焦點事件 $("#e11").click(function() { $("#e11").val(["AK","CO"]).trigger("change"); }); 官網文檔地址是:http://select2.github.io/select2/#documentation。說再多也沒用,最后我們來個實例來證明一下ajax請求遠程數據,以截圖為準: ? miniNameInModal.select2({ajax: {url:Api.getMiniClassListForJqGrid,//當用戶打開控件時,Select2會向指定的URL發出請求(除非有 minimumInputLength設置),并且每當用戶在搜索框中輸入時也是如此。默認情況下,它將以查詢字符串參數的形式發送以下內容:data: function (term,page) {// term :搜索框中的當前搜索詞。var query = {name: term,row:20,page:page,search: term,type: 'public'}//Query parameters will be ?search=[term]&type=public&name=[term]return query;},results:function(data,page){ //data是后端返回的原始數據,data.rows的數據格式[{…}, {…}, {…}, {…}, {…}];debuggerpage === 1 && (dataObjs = []);var result=[];$(data.rows).each(function(i,item){var row=[],dataObj={};row['id']=item.miniClassId;row['text']=item.name;dataObj = $.extend({},item,{totalLastClassHours:item.totalClassHours-item.consume});dataObjs.push(dataObj);//item對象增加一個屬性。 result.push(row);});if((data.rows).length>0){return {results :result,more:true};//返回一個數組,result數組的格式是[[],[],[]]}else{return {results :result};}}}}); miniNameInModal.select2({placeholder :'請選擇班課',ajax :{url :function(term,page){return Api.getMiniClassListForJqGrid+'?name='+(term||'')+'&rows=20&page='+page;},results:function(data,page){page === 1 && (dataObjs = []);var result=[];$(data.rows).each(function(i,item){var row=[],dataObj={};row['id']=item.miniClassId;row['text']=item.name;dataObj = $.extend({},item,{totalLastClassHours:item.totalClassHours-item.consume});dataObjs.push(dataObj);result.push(row);});if((data.rows).length>0){return {results :result,more:true};}else{return {results :result};}}}})
?
// 初始化選項function initSelectOptions(){//選學員// findStudentAutoComplate.select2({// placeholder: '請選擇學員',// ajax: {// url: function (term, page) {// return Util.getURLData(Api.getStudentListShortly + '?name=' + (term || '') + '&rows=20&page=' + page);// },// results: function (response) {// var result = [];// var data = response.data.datas;// $(data).each(function (i, item) {// var row = [];// row['id'] = item.id;// row['text'] = item.name;// result.push(row);// });// if (data.length > 0) {// return { results: result, more: true };// } else {// return { results: result };// }// }// }// }); } $('#reviewUser').select2({width: '100%', formatSelection: function (data, container, escapeMarkup) {$('#checkout-form').valid();return data ? escapeMarkup(data.text) : undefined;}}); $('#approveUser').select2({formatSelection: function (data, container, escapeMarkup) {$('#checkout-form').valid();return data ? escapeMarkup(data.text) : undefined;}}); currentStudentName.select2({placeholder :'請選擇學員',ajax :{url:function(term,page){return Api.getOneOnOneStudentList+'?blCampusId=' + currentCampusId + '&name='+(term||'')+'&_search=true&sord=asc&rows=20&page='+page;},dataType: 'json',multiple: true,results:function(data,page){page === 1 && (dataObjs = []);var result=[];$(data.rows).each(function (i, item) {var dataObj={},row=[];row['id']=item.id;row['text']=item.name;dataObj = $.extend({},item);dataObjs.push(dataObj);result.push(row);});if((data.rows).length>0){return {results :result,more:true};}else{return {results :result};}}}}) //設置select2 placeholder currentAddressSelect.select2({formatNoMatches: function () {return '暫無數據' + '<a class="link pull-right">添加小區</a>';}}); // 加載學員下拉框$('form[id=frm] select[name=studentId]').select2({formatNoMatches: '找不到匹配的數據'}); schoolEl.select2({formatNoMatches: function () {if(Index.authFuncBtnTags.indexOf('BTN_CREATE_SCHOOL')!=-1){//加了權限才顯示return '暫無數據' + '<a class="addSchool link pull-right">添加學校</a>';}else{return '暫無數據';}}}); placeholder: "請輸入",minimumInputLength: 1,separator: ",", // 分隔符maximumSelectionSize: 5, // 限制數量initSelection: function(element, callback) { // 初始化時設置默認值 },createSearchChoice: function(term, data) { // 創建搜索結果(使用戶可以輸入匹配值以外的其它值)return {id: term.mid,text: term.name};},formatSelection: function(item) {return item.name;//注意此處的name,要和ajax返回數組的鍵值一樣}, // 選擇結果中的顯示formatResult: function(item) {return item.name;//注意此處的name}, // 搜索列表中的顯示 ajax: {url: "{:U('Admin/Member/getzj')}", // 異步請求地址dataType: "json", // 數據類型data: function(term, page) { // 請求參數(GET)return {q: term};},results: function(data, page) {return data;}, // 構造返回結果escapeMarkup: function(m) {return m;} // 字符轉義處理}//轉介紹類型的時候,自動帶出轉介紹人的select2
/*flag0 代表返回placeholder1 代表返回無數據提示2 代表返回初始提示無 代表返回api*/function getAutoCompleteApi(cusOrg, flag) {// options in getCusOrgOnlyIntroduce is hardcodedvar apiList = [EduBoss.serviceApi.getAutoCompeleteCustomerForAll, EduBoss.serviceApi.getUserAutoCompleteForAll, EduBoss.serviceApi.getAutoCompleteStudentForCustomerNewIntroduce];var tipList = ['請選擇客戶', '請選擇員工', '請選擇學員'];var cusList = ['客戶轉介紹', '員工轉介紹', '學員轉介紹'];var noDataTips = ['沒有找到相關客戶', '沒有找到相關員工', '沒有找到相關學員'];var initTips = ['輸入客戶姓名/手機號', '輸入員工姓名', '輸入學員姓名'];var index = $.inArray(cusOrg, cusList);if (index === -1) return '';if (flag === 0) {return tipList[index];} else if (flag === 1) {return noDataTips[index];} else if (flag === 2) {return initTips[index];} else {return apiList[index];}}function safeDestroyAutocomplete(sel) {var $el = $(sel);if ($el.hasClass("select2-offscreen")) {$el.select2('destroy');}} $("#customerNewIntroduceType").on("change", function (event) {debuggervar introducerSel = $('#introducer');safeDestroyAutocomplete(introducerSel);cusNewIntroTypeName = $(this).val();var text = $(this).find(":selected").text(),url = getAutoCompleteApi(text);if (url) {safeDestroyAutocomplete(introducerSel);Util.normalSelect2(introducerSel, {placeholder: getAutoCompleteApi(text, 0),api: url,labelFormat: function (data) {//data =?"Wed Jan 17 11:44:54 CST 2018(),1"debugger// console.log(data+"yys")return data ? data.substring(0, data.indexOf(',')) : '';},results:function(data){debuggerconsole.log(data+"uud")},noDataTips: getAutoCompleteApi(text, 1),initTips: getAutoCompleteApi(text, 2),})} else {safeDestroyAutocomplete(introducerSel);}})modal.on('show.bs.modal', function () {//要等modal出來之后,才能再找到對應的元素,觸發綁定的change事件。 如果是loadHtmlModalWithParameters的形式加載modal,那么load的Modal里邊需要加上//Util.modalExec(modal.parents('.modal'), initData);以上這一句要寫在initEven的后面。等modal完全加載出來之后再iniData(),initData之后就不需要另外的initData了。 var introducerSel = $('#introducer');safeDestroyAutocomplete(introducerSel);$("#customerNewIntroduceType").change();});
<div class="col-md-6 form-group"><label class="must-input">轉介紹類型</label><div><select name="customerNewIntroduceType" class="required form-control select2" data-from="customerNewIntroduceType" id="customerNewIntroduceType">//加了select2回顯的時候為什么要change一下呢? //如果是普通的select則不需要change,使用Util.fillElmentValueByTag(data, 'data-from', null, modal);就可以回顯出來了。 </select></div> </div>
//修改jqgrid.on('click', '.mod', function () {var id = $(this).parents('tr').attr('data-id');modal.find("#myModalLabel").text("修改轉介紹");$.get(Api.getCustomerNewIntroduct, {customerNewIntroductId:id}, function (res) {if (res.resultCode === 0) {var data = res.data;Util.fillElmentValueByTag(data, 'data-from', null, modal);//followUpUserId.prop('disabled', true);recordDate.prop('disabled', true);$("#customerName").prop('disabled', true);contract.prop('disabled', true);modal.modal('show');modal.find("#moreCustomerInfo").hide();$("#customerNewIntroduceType").change();$("#introducer").prev("div").find(".select2-chosen").text(data.introducer);oldCustomerNewIntroduceType = data.customerNewIntroduceType;oldIntroducer = data.introducer;}})})
?
? normalSelect2: function (item, options) {options = options || {};item.select2({placeholder: options.placeholder || '請選擇',ajax: {url: function (term, page) {if (!term) return [];var api = options.api;if ($.type(api) === 'function') api = api();return Util.getURLData(api + (/\?/g.test(api) ? '&' : '?') + 'term=' + (term || ''));},results: function (data, page) { //data = (7) [{label: "sdfxf(),86305", value: "86305"}, {…}, {…}, {…}, {…}, {…}, {…}], page = 1debuggerreturn {results: data.map(function (item) {return {id: item.value,text: options.labelFormat ? options.labelFormat(item.label) : item.label}})};}},formatNoMatches: function (term) {return term ? (options.noDataTips || '暫無數據') : (options.initTips || '輸入關鍵字后查詢');}})},?
轉載于:https://www.cnblogs.com/susan-home/p/9214269.html
總結
以上是生活随笔為你收集整理的select2 api参数的文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js两个数组对象通过相同元素匹配筛选
- 下一篇: Ubuntu之镜像iso安装系统