【问题标题】:Styling individual select2 tags为单个 select2 标签设置样式
【发布时间】:2016-06-14 22:08:15
【问题描述】:

我正在尝试根据用户是否创建标签(应用红色 .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 就会删除样式类引用。谁能告诉我如何将样式应用于标签而不选择2删除它们?非常感谢!

【问题讨论】:

    标签: jquery-select2 jquery-select2-4


    【解决方案1】:

    阅读文档并遵循 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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多