简体   繁体   English

如何在select2的所选项目中显示图标?

[英]How to display an icon in the chosen item of select2?

I have a select2 plugin with the <options> formated. 我有一个带有<options>格式的select2插件。 I'm adding a fontawesome icon at the right. 我在右侧添加了一个fontawesome图标。

The problem is that when I select any item which has the icon, the icon is not displayed in the current item choosed, when the dropdown is closed. 问题是,当我选择带有图标的任何项目时,关闭下拉列表时,该图标不会显示在所选的当前项目中。 How could I solve it? 我该怎么解决? May be is wrong the format function? 可能是错误的格式功能?

Here is a jsfiddle where you can try: http://jsfiddle.net/uAnLJ/18/ 这是一个可以尝试的jsfiddle: http : //jsfiddle.net/uAnLJ/18/

JS JS

$("#mysel").select2({
    width: "100%",
    formatResult: function(referencia) {
        if (!referencia.id) return referencia.text; // optgroup

        if ($(referencia.element).data('active') == "1") {
            return referencia.text + "<i class='fa fa-check-circle'></i>";
        } else {
            return referencia.text;
        }
    }
});

CSS CSS

body {
    padding: 20px;
}

.fa-check-circle{
    float: right;
    position: relative;
    line-height: 20px;
}

HTML HTML

<select id="mysel">
    <optgroup label="First group">
        <option value="0" data-active="1">Hello</option>
        <option value="1" data-active="0">Stack</option>
    </optgroup>
    <optgroup label="Second group">
        <option value="2" data-active="1">Overflow</option>
        <option value="3" data-active="1">Friends</option>
    </optgroup>
</select>

You need to use formatSelection if you want to change the look of the selected element as well: 如果还想更改选定元素的外观,则需要使用formatSelection

formatSelection: function (referencia) {
    if ($(referencia.element).data('active') == "1") {
        return referencia.text + "<i class='fa fa-check-circle'></i>";
    } else {
        return referencia.text;
    }
}

Updated fiddle: http://jsfiddle.net/uAnLJ/22/ 更新的小提琴: http : //jsfiddle.net/uAnLJ/22/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM