问题
I'm trying to style individual select2 tags using Bootstrap's button styles (.btn-primary and .btn-danger) based on if the user created a tag (applying the red .btn-danger style) or if the user selected a existing tag (applying the blue .btn-primary style.
I've tried to apply the style during the select event (select2:select) event:
$("#ticker_select").on('select2:select', function(e) {
// If the e.params.data.id equals e.params.data.txt,
// then it is a user-created tag!
if (e.params.data.id == e.params.data.text) {
// User-created tag; Mark the tag red
$(".select2-selection__choice[title='" + e.params.data.text + "']").addClass('btn-danger');
}
else {
// User-selected tag; Mark the tag blue
$(".select2-selection__choice[title='" + e.params.data.text + "']").addClass('btn-success');
}
});
I see that the styling applied to the tag but as soon as the event ends, select2 removes the style class reference. Can anyone please show me how to apply the styles to tags without select2 removing them? Many thanks!
回答1:
Reading the documentation & following a suggestion from IRC, there's a templateSelection option in select2. In my case, I would do something similar to this:
function template(data, container) {
// If the ID and text properties are NOT equal, user didn't create tag
if (data.id != data.text) {
container.addClass("btn-primary");
}
else container.addClass("btn-danger");
return data.text;
}
$('select').select2({
templateSelection: template
});
来源:https://stackoverflow.com/questions/37822933/styling-individual-select2-tags