样式化各个select2标签

时间:2016-06-14 22:08:15

标签: jquery-select2 jquery-select2-4

我正在尝试使用Bootstrap的按钮样式( .btn-primary .btn-danger )根据用户是否创建了标记来设置单个select2标记的样式(应用红色 .btn-danger 样式)或者如果用户选择了现有标记(应用蓝色 .btn-primary 样式。

我试图在select事件(select2:select)事件中应用样式:

$("#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');
        }
    });

我看到样式应用于标记,但是一旦事件结束,select2就会删除样式类引用。任何人都可以告诉我如何将样式应用于标签而不用select2删除它们?非常感谢!

1 个答案:

答案 0 :(得分:2)

阅读文档&根据IRC的建议,select2中有 templateSelection 选项。就我而言,我会做类似的事情:

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
});
相关问题