Selectable optgroups in Select2

前端 未结 1 1865
离开以前
离开以前 2020-12-05 08:04

I want to create multilevel select2 options with indentation but I don\'t want to use optgroup elements for this because I want to allow select also main catego

1条回答
  •  星月不相逢
    2020-12-05 08:46

    You're correct in recognizing that Select2 does not carry the CSS classes from the tags to the results list. This mostly has to do with not explicitly tying the results list to existing tags, and also having a set of sensible defaults. It's easier to add the ability to transfer classes afterwards than it is to remove them.

    You can do this by overriding templateResult and getting the original option from data.element (where data is the first parameter).

    $('.select2').select2({
      templateResult: function (data) {    
        // We only really care if there is an element to pull classes from
        if (!data.element) {
          return data.text;
        }
    
        var $element = $(data.element);
    
        var $wrapper = $('');
        $wrapper.addClass($element[0].className);
    
        $wrapper.text(data.text);
    
        return $wrapper;
      }
    });
    .l2 {
      padding-left: 1em;
    }
    
    
    
    
    
    

    Note that I am also using padding-left instead of text-indent, which is what Select2 usually uses for nested options.

    0 讨论(0)
提交回复
热议问题