我正在用 select2 做标记
我对 select2 有这些要求:
- 我需要使用 select2 ajax 搜索一些标签
- 我还需要在 select2 中使用“标签”,它允许不在列表中的值(Ajax 结果)。
这两种情况都是独立工作的。但是连接在一起的 aJax 值只会被填充。如果我们键入不在列表中的任何其他值,则会显示“未找到匹配项”
我的场景如果用户键入任何不在列表中的新值,允许他们组成自己的标签。
有什么方法可以让它工作吗?
最佳答案
Select2 具有函数“createSearchChoice”:
Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.
您可以通过以下方式实现您想要的:
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true
这是一个更完整的答案,它将 JSON 结果返回给 ajax 搜索,并允许从该术语创建标签,如果该术语未返回任何结果:
$(".select2").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: '/path/to/results.json',
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
关于javascript - 在 select2 中使用 AJAX 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229768/