我正在使用 Select2 来管理大量数据。用户表示希望能够将列表粘贴到 Select2 字段,以便一次选择各种项目,而不是手动输入和匹配列表中的每个项目。
我试图用它tokenSeparators
来分隔列表中的项目。这和文档中关于令牌的演示让我相信我希望做的事情是可能的,但到目前为止我还没有感到高兴。
我用来实例化 Select2 的代码是:
$('input').select2({
width: 'element',
matcher: function (term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) === 0;
},
minimumInputLength: 3,
multiple: true,
data: tagList, // tagList is an array of objects with id & text parameters
placeholder: 'Manage List',
initSelection: function (element, callback) {
var data = [];
$.each(function () {
data.push({id: this, text: this});
});
callback(data);
},
tokenSeparators: [',', ', ', ' ']
});
只是为了澄清,在所有其他方面, select2 字段都有效。只是将列表粘贴到字段中时没有任何匹配项。我想测试粘贴列表中的所有项目。这可能吗?如果可以,怎么做?
编辑: 我尝试了以下代码,但它似乎不起作用:
$('body').on('paste', '#s2id_list-unitids .select2-input', function () {
var that = this;
setTimeout(function () {
var tokens = that.value.split(/[\,\s]+/);
$('#list-unitids').val(tokens, true);console.log($('#list-unitids').select2('val'));
}, 1);
});
这是我创建的小提琴:http: //jsfiddle.net/KCZDu/。