选择 2 ->添加数据而不替换内容 [英] SELECT2 -> Add data without replacing content
问题描述
我看过其他一些主题,但没有那么具体.这并不是我认为很难的事情,但我不确定如何去做.
I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.
目前我将 Select2 用于标记系统,在它旁边我有建议的标签,用户可以点击这些标签并将其添加到框中.
Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.
相反,每个标签都在替换内容并添加自身.
Instead, each tag is replacing the content and adding itself.
我需要将添加内容附加到框中,而不替换其中已有的内容.
I need the adding to be appended into the box without replacing what's already in there.
这是我的代码:
$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
数据是通过 AJAX 拉取的,每个建议标签都有一个跨度.
The data is being pulled through via AJAX with a span around each suggested tag.
希望我足够清楚.
总结:我希望能够点击每个标签"并添加它,而不是替换框中已有的内容.
Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.
谢谢
推荐答案
您应该能够通过简单的方式做到这一点:
You should be able to do that with simple:
var test = $('#test');
$(test).select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate"},
{id:3,text:"invalid"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px"
});
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
工作示例:http://jsfiddle.net/z96Ca/
这篇关于选择 2 ->添加数据而不替换内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!