gpt4 book ai didi

javascript - 如何在select2的选中项中显示一个图标?

转载 作者:太空宇宙 更新时间:2023-11-04 13:21:33 24 4
gpt4 key购买 nike

我有一个带有 <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>

最佳答案

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

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

更新 fiddle :http://jsfiddle.net/uAnLJ/22/

关于javascript - 如何在select2的选中项中显示一个图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24046201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com