设置单个select2标签的样式 [英] Styling individual select2 tags

查看:637
本文介绍了设置单个select2标签的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我尝试在select事件(select2:select)事件期间应用样式:

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');
        }
    });

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

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!

推荐答案

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

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
});

这篇关于设置单个select2标签的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆