根据选项的数据属性在 select2 中显示图像

Displaying images in select2 based on data attributes on options

我想用 Select2 做一些事情,比如 templating example 但我没有使用一组预定义的图像,所以需要稍微修改它。

我想我可以添加我想显示的图像的路径,每个选项都有一个数据属性,然后我可以使用 element.attr('data-thumb') 而不是 element.value 但是当我这样做时我得到element.attr 不是函数

HTML

<select>
  <option value="A" data-thumb="a.jpg">A</option>
  <option value="B" data-thumb="b.jpg">B</option>
  <option value="C" data-thumb="c.jpg">C</option>  
</select>

JS

function productStyles(selection) {
    if (!selection.id) { return selection.text; }
    var $selection = $(
      '<img src="' + selection.element.attr('data-thumb')+ '"> ' + selection.text
    );
    return $selection;
};

$('.img-changer').select2({
    templateResult: productStyles
});

是否可以使用 .element 访问数据属性,或者我是否需要另一种方法,如果需要,那会是什么?

<option class="img class" value=""></option>    

function formatSelect2(o) {
if (!o.id)
    return o.text;
else
    return $("<span><i class='" + $(o.element).attr("class") + "'></i> " + o.text + "</span>"); }     

$('#Category-Add').select2({
        width: '100%',
        templateResult: formatSelect2,
        templateSelection: formatSelect2,
        theme: "classic"
    });

原来我需要的是var thumb = $(selection.element).data('thumb')

function productStyles(selection) {
  if (!selection.id) { return selection.text; }
    var thumb = $(selection.element).data('thumb');
    if(!thumb){
      return selection.text;
    } else {
      var $selection = $(
    '<img src="' + thumb + '" alt=""><span class="img-changer-text">' + $(selection.element).text() + '</span>'
  );
  return $selection;
  }
}