【问题标题】:How to display an icon in the chosen item of select2?如何在select2的选中项中显示一个图标?
【发布时间】:2014-06-04 19:44:50
【问题描述】:

我有一个带有 <options> 格式的 select2 插件。我在右边添加了一个很棒的图标。

问题是当我选择任何具有图标的项目时,当下拉菜单关闭时,图标不会显示在当前选择的项目中。我该如何解决?可能是格式功能不对?

这是一个 jsfiddle,您可以尝试:http://jsfiddle.net/uAnLJ/18/

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

body {
    padding: 20px;
}

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

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>

【问题讨论】:

    标签: javascript jquery html css jquery-select2


    【解决方案1】:

    如果您还想更改所选元素的外观,则需要使用formatSelection

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 2019-05-28
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多