我使用select2插件。标签输入的工作方式如下:
HTML:
<input type="hidden" id="tags" value="tag1,tag2" style="width: 400px;">
JS:
$('#tags').select2({
tags: true,
tokenSeparators: [','],
createSearchChoice: function (term) {
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
ajax: {
url: 'https://api.myjson.com/bins/444cr',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
},
// Take default tags from the input value
initSelection: function (element, callback) {
var data = [];
function splitVal(string, separator) {
var val, i, l;
if (string === null || string.length < 1) return [];
val = string.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
return val;
}
$(splitVal(element.val(), ",")).each(function () {
data.push({
id: this,
text: this
});
});
callback(data);
},
// Some nice improvements:
// max tags is 3
maximumSelectionSize: 3,
// override message for max tags
formatSelectionTooBig: function (limit) {
return "Max tags is only " + limit;
}
});
文件Json输出:
[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"},{"id":"tag3","text":"tag3"},{"id":"tag4","text":"tag4"}]
This Worked,但我有这样的新数组文件:
["Aus","Bng","Dsa","Ymn","Was","Mip"]
使用此文件select2不起作用而不显示标签。我怎样才能为我的文件编辑js?
工作DEMO:http://jsfiddle.net/X6V2s/2/
没有工作的DEMO:http://jsfiddle.net/X6V2s/5/