您的位置:首页 > 其它

Select2开源项目如何轻松加入到项目中

2017-06-09 11:37 477 查看

1.Select2控件的介绍

Select2为您提供了一个可定制的选择框,支持搜索、标记、远程数据集、无限滚动以及许多其他高度使用的选项。

2.Select2控件下载地址

https://github.com/select2/select2/releases

我在该页面下载的 https://github.com/select2/select2/releases下载的源代码,解压后目录结构如下:



3.Select2引入方式

通常情况下我们只需要引用select2的js和css,

<scriptsrc="<%=realPath%>/res/select2/js/select2.full.min.js"></script>

<link href="<%=realPath%>/res/select2/css/select2.css" rel="stylesheet" />

若需要使用中文提示语,则需要引入中文国际化的js如下:(注意事项,zh-CN.js引用一定要在select2.full.min.js"下面,防止中文国际化的JS不起作用)

<script src="<%=realPath%>/res/select2/js/i18n/zh-CN.js"></script>

同时需要配置显示语言如下:

$(".js-data-example-ajax").select2({

language: "zh-CN"});

4.要想使用select2需要执行如下代码

$(".js-example-basic-single").select2();


<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>


5.select2控件的ajax使用格式如下:

$(".js-data-example-ajax").select2({

language: "zh-CN",

minimumInputLength: 1,   
//搜索框至少要输入的长度,此处设置后需输入才显示结果

maximumSelectionLength: 32,
//设置最多可以选择多少项

ajax: {

    url:"<%=realPath%>/provider_list/listAjax",

    type:"post",

    dataType: 'json',

    delay: 250,

    data: function (params) {

      return {

        name: params.term
// search term

      };

    },

    processResults:
function (data, params) {

        for (var i = 0; i < data.list.length; i++) {

        data.list[i].id = data.list[i].id;

        data.list[i].text = data.list[i].name;

                } 

      return {

        results: data.list

      };

    },

    cache: true

  },

allowClear: true,

placeholder:'请输入后选择',//默认文字提示

escapeMarkup: function (markup) {return markup; },
// 让template的html显示效果,否则输出代码

templateResult:
function formatRepo(repo){return repo.text;},// 自定义下拉选项的样式模板

    templateSelection:
function formatRepoSelection(repo){return repo.text;}    // 自定义选中选项的样式模板

});
select2控件change事件监听方式如下:

$(".js-data-example-ajax").on("change",function (e) {

//id  $(this).val() providerName $(this).text()

$("#product_name").empty();

$("#product_name").append("<option value=''>"+"请选择"+"</option>");

$("#product_type").empty();

$("#product_type").append("<option value=''>"+"请选择"+"</option>");

var data = {providerId:$(this).val()};

$.post("<%=realPath%>/product/ajaxFindProductListByProviderId", data ,function(result){

if(result && result.length>0){

for(var a=0; a<result.length; a++){

$("#product_name").append("<option value='"+result[a].id+"'>"+result[a].productName+"</option>");

$("#product_type").append("<option value='"+result[a].id+"'>"+result[a].productNum+"</option>");



}else{

return layer.msg(result.message,function(){});

}

},"json");

});

select使用定义

<selectclass="js-data-example-ajax form-control" style="width:100%;"></select



更多使用实例可以查看官网:http://select2.github.io/examples.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息