用了這麼久的Select2插件,也該寫篇文章總結總結。
在我的印象裏Select2有2個版本,最新版本有一些新的特性,並且更新了一下方法參數,比最初版本要好看一些,本文針對新版本。
一.文件需要引入select2.full.js、select2.min.css(4.0.1版本)和jquery.1.8.3及以上
最新版本的select2如果引用的jquery版本較低的話,某些功能無法正常使用。比如:清除功能allowClear: true
最新版本請使用標籤
二.placeholder
placeholder佔位提示文字,如果需要清楚功能,則必須設置placeholder。
三.加載本地數據
select2默認的數據屬性是id、text,新版本可以自定義,但還是用默認的比較好。所以提供的json中最好轉換爲id、text形式,當然可以添加其他屬性。
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$("#c01-select").select2({
data: data,
placeholder:'請選擇',
allowClear:true
})
四.加載遠程數據
$("#c01-select").select2({
ajax: {
url: "data.json",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
說明:
q: params.term 查詢參數(params.term表示輸入框中內容,q發生到服務器的參數名;所以這裏你可以添加自定義參數,如:stype:’person’)
processResults中results: data返回數據(返回最終數據給results,如果我的數據在data.res下,則返回data.res。這個與服務器返回json有關)
minimumInputLength 最小需要輸入多少個字符才進行查詢,與之相關的maximumSelectionLength表示最大輸入限制。
escapeMarkup字符轉義處理
templateResult返回結果回調function formatRepo(repo){return repo.text},這樣就可以將返回結果的的text顯示到下拉框裏,當然你可以return repo.text+”1”;等
templateSelection選中項回調function formatRepoSelection(repo){return repo.text}
關於返回的 json的格式:select2默認json格式爲[{id:1,text:’text’},{id:2,text:’text’}],新版嚴格要求這樣的格式,當然你可以添加列,如:[{id:1,text:’text’,name:’liu’}]
五.獲取選中項
var res=$("#c01-select").select2("data")[0] ; //單選
var reslist=$("#c01-select").select2("data"); //多選
if(res==undefined)
{
alert("你沒有選中任何項");
}
if(reslist.length)
{
alert("你選中任何項");
}
六.清空選擇項和設置不可用
//清空選擇
$("#c01-select").val(null).trigger("change");
$("#c01-select").val("你的placeholder").trigger("change");//或者
//disabled
$("#c01-select").prop("disabled", false);//可用
$("#c01-select").prop("disabled", true);//不可用
七.啓用多選
$("#c01-select").select2({
data:data,
multiple: true
});
八.下面簡單說明新版與老版對比
結果回調和選中回調名稱:formatResult、formatSelection(老版);templateResult、templateSelection(新版)
初始化:
//老版,注意如果初始化時文本框中本身沒有值(爲空),則不會觸發該方法
initSelection: function (element, callback) {
var id = $(element).val();
var data = { id: id, text: id};//這裏是初始化的數據,你可以通過id來從服務器上獲取(ajax),再裝載進去
callback(data);
}
//新版,直接給select添加option
$("#id").append(new Option("Jquery", 10001, false, true));
//或者
$("#id").append("<option value='10001'>Jquery</option>");
3.獲取或設置值:
select2("val")(老版);
$("select").val()(新版)
推薦使用
var res = $("#id").select2("data");
//返回數組,單選就取res[0];好處是不進可以獲取id、text還可以獲取其他屬性,如res[0].names
4.停用或啓用:
$("select").enable(false);(老版);
$("select").prop("disabled", true);(新版)
5.主題樣式:新版的樣式已經更新,但如果想使用老版樣式則可以設置 theme: “classic”