以下代码适用于select2版本:3.X,但当我使用“https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js”和“https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css”时,它不会添加值:
var data = [];
for(var i = 0; i < 10000; i++){
data.push({id: ""+i, text: ""+i});
}
$("input").select2({
initSelection: function(element, callback) {
var selection = _.find(data, function(metric){
return metric.id === element.val();
})
callback(selection);
},
query: function(options){
var pageSize = 100;
var startIndex = (options.page - 1) * pageSize;
var filteredData = data;
if( options.term && options.term.length > 0 ){
if( !options.context ){
var term = options.term.toLowerCase();
options.context = data.filter( function(metric){
return ( metric.text.toLowerCase().indexOf(term) !== -1 );
});
}
filteredData = options.context;
}
options.callback({
context: filteredData,
results: filteredData.slice(startIndex, startIndex + pageSize),
more: (startIndex + pageSize) < filteredData.length
});
},
placeholder: "Select a metric"
});
这里是jsfiddle的链接: http://jsfiddle.net/Z7bDG/1/