select2的基本用法
--select2
https://select2.org/
https://select2.org/data-sources/ajax
公司有個項目需要用到類似百度搜索功能的下拉框,自然想到使用select2。
先看下select2的效果圖,如下:
下來簡單介紹下這個控件的基本用法,主要簡單介紹下遠程加載數據;
1.首先引入需要的文件:select2.full.js、select2.min.css(4.0.1版本)和jquery.1.8.3及以上.
2.遠程加載數據示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
與普通ajax調用不同的是data和processResults;
注意 data方法裏面有個q:params.term這個是幹什麼的呢?其實這是獲取當前輸入值的,也就是上圖中的“1”。這裏的q:params.term;使用的時候直接照搬就行;當然你也可以把q換成你喜歡的參數名字。
processResults裏面就是從後臺獲取數據結果的;最終返回的數據的格式一般是這樣子:"[{id:0,text:'a'},{id:1,text:'b'}]"(select2默認的數據屬性是id、text聽說新版本可以自定義);
minimumInputLength同字面意思,即限制最少輸入一個字符;
placeholder等同文本框的placeholder;
allowClear:true表示允許清除選中的內容,即爲true的時候圖中的“1”右邊會出現一個“x”,點擊後可以清除掉輸入框的內容;
本人在使用的時候在這裏遇見了一個大坑,就是你寫了allowClear:true,但是點擊上面的“x“後,沒有反應,納尼,嘛情況!
網上查了下,有人說,要allowClear:true生效,必須要設置placeholder屬性,可是我寫了呀。難道js文件和select2版本不匹配?
嘗試個多個版本的js和select2還是這問題;
今天突然看到一篇外國的文章,解決了這個問題,其實很簡單就是要allowClear:true生效,必須在<select>標籤中添加一個空的<option>節點(可以不設置placeholder屬性,因爲控件有默認值);如下:
<select id="simple" style="width: 120px;">
<option></option>
</select>
那這是爲什麼呢 ?原因是The first option must be empty in order to get placeholderworking!
<select class="select2_category form-control" multiple id="cityselect" tabindex="4" style="width: 120px" >
<option value=""></option>
<!--<option value="20" selected="selected">TOP20</option>-->
<!--<option value="30">TOP30</option>-->
<!--<option value="50">TOP50</option>-->
</select>
$('#cityselect').select2({
placeholder: '城市',
allowClear: true,
escapeMarkup: function(m) {
return m;
}
});
$("#cityselect").prop("disabled", true);
var getCity = function(country) {
$("#cityselect").empty();
$("#cityselect").append("<option value=''></option>");
if($("#countryselect").val() == "" || $("#countryselect").val() == null){
return;
}
$.ajax({
type: "GET",
url: ROOT_PATH+"tt/api/getCity",
data: {country : ($('#countryselect').val()!=null?$('#countryselect').val()+"":"")},
success: function (result) {
$("#cityselect").prop("disabled", false);
var cities = result.split(",");
for (var entry in cities) {
$("#cityselect").append("<option value='" + cities[entry] + "'>" + cities[entry] + "</option>");
}
},
error: function () {
toastr['error']("獲取城市列表錯誤", "警告");
}
});
};