浅谈select2使用

select2有很多的属性、事件,列举一些常用的栗子

引入select2插件后,最简单的使用方式,不带ajax请求

$("#demo").select2({
    placeholder: "please select demo",
    allowClear: true,
                data: [{id: 10001, text: 'demoa'},
                        {id: 10002, text: 'demob'},
                        {id: 10003, text: 'democ'}]
        });
placeholder             输入框站位符
allowClear: true,       指定有占位符时允许清除

使用ajax请求

$("#demo").select2({
            placeholder: "选择...",
            multiple: true,         //是否多选
            allowClear: true,    
            ajax: {
                url: "url",        //请求地址
                type: "post",      //请求方式
                formatSelection: function(item){
                   return item.name;   //显示选择对象属性name
               },
               formatResult: function(item){
                  return item.name;   //下拉时显示name属性
             }
        });

select2分页

$("#demo").select2({
            placeholder: "选择...",
            multiple: true,         //是否多选
            allowClear: true,    
            ajax: {
                url: "url",        //请求地址
                type: "post",      //请求方式
                data:function(term, page){
                    return {
                        "term": term,    //模糊查询
                        "start": ( page - 1) *_LENGTH,//开始
                        "length": _LENGTH //长度                                         
                    };
                },
                results: this.proxy(function(response, page){
                    if(response.success){
                        return {
                            "results": response.data,  //返回数据
                            "more": response.data.length > (page * _LENGTH) //下拉结果判断
                        };
                    }
                    else{
                        alert(response.reason);
                    }
                })
            },
                formatSelection: function(item){
                   return item.name;   //显示选择对象属性name
               },
               formatResult: function(item){
                  return item.name;   //下拉时显示name属性
             }
        });

select2事件,静态数据为例,动态写法一样

$("#demo").select2({
    placeholder: "please select demo",
    allowClear: true,
                data: [{id: 10001, text: 'demoa'},
                        {id: 10002, text: 'demob'},
                        {id: 10003, text: 'democ'}]
        }).on("change",function(){
        //值发生改变时触发,这里写需要调用的fuction
        //常用事件有,select2-open  select2打开时触发
        //select2-close   关闭时触发
        //select2-selecting  选中时触发
    });

你可能感兴趣的:(JavaScript)