问题
I am using Select2 to setup multi-select tag type fields in my application. I know which CSS attribute changes the colors of the selection box once it is placed in the select field:
selection box color
.select2-container--default .select2-selection--multiple .select2-selection__choice {
background-color: #e4e4e4;
border: 1px solid #aaa;
border-radius: 4px;
cursor: default;
float: left;
margin-right: 5px;
margin-top: 5px;
padding: 0 5px
}
What I am trying to figure out is how to have this change based on the selection a user makes. The selection list is pre-defined.
Tried something like this:
JavaScript to initialize / change box color
$(document).ready(function () {
$('#test').select2();
$('.select2-container--default .select2-selection--multiple .select2-selection__choice').each(function () {
var title = $(this).attr('title');
console.log(title);
if (title === 'Breakfast') {
$(this).parent().css({ 'background-color': "green" });
}
if (title === 'Brunch') {
$(this).parent().css({ 'background-color': "red" });
}
if (title === 'Lunch') {
$(this).parent().css({ 'background-color': "blue" });
}
});
});
This does not appear to work. Has anyone tried styling the tag boxes for Select2?
回答1:
Change $(this).parent().css('background-color', 'green');
by $(this).parent().css({ 'background-color': "green" });
And the same with the rest.
来源:https://stackoverflow.com/questions/45946496/changing-the-background-color-of-a-select2-selection-within-the-select-field