gpt4 book ai didi

javascript - 如何在 select2 中添加新标签?

转载 作者:行者123 更新时间:2023-12-03 10:21:35 25 4
gpt4 key购买 nike

我正在尝试从我的 api 获取标签。一切正常,但我无法添加新标签。这是我尝试过的:

$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});

通过使用上面的代码,我只能获取标签,但无法添加新标签。我如何添加新标签?

请帮忙

最佳答案

$("#e11_2").select2({
createSearchChoice: function(term, data) {

if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

您必须创建一个像 createSearchChoice 这样的函数,它返回一个带有“id”和“text”的对象。在其他情况下,如果返回未定义,则不会创建选项。

关于javascript - 如何在 select2 中添加新标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com