javascript 如何将图标附加到select2中的选定项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23640521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append an icon to selected item in select2?
提问by harrison4
I'm using fontawesome, and I want to add or remove an icon to the selected item. So I did this: http://jsbin.com/nasixuro/7/edit(Thanks to @Fares M.)
我正在使用 fontawesome,我想为所选项目添加或删除图标。所以我这样做了:http: //jsbin.com/nasixuro/7/edit(感谢@Fares M.)
JS
JS
$(document).ready(function () {
function format_select2_icon(opti) {
if (!opti.id) return opti.text; // optgroup
if ($(opti.element).data('icon') == "1") {
return opti.text + " <i class='fa fa-check'></i>";
} else {
return opti.text;
}
}
$("#sel").select2({
escapeMarkup: function(m) { return m; },
formatResult: format_select2_icon,
formatSelection: format_select2_icon
});
$("#addok").click(function() {
actual_value = $("#sel").find(':selected').text();
if (actual_value.indexOf(" <i class='fa fa-check'></i>") > -1){
alert("asd");
return;
}
newtext = actual_value + " <i class='fa fa-check'></i>";
$("#sel").find(':selected').text(newtext).change();
});
$("#removeok").click(function() {
actual_value= $("#sel").find(':selected').text();
indexOk=actual_value.indexOf(" <i class='fa fa-check'></i>");
if (indexOk > -1){
newtext =actual_value.substring(0, indexOk);
$("#sel").find(':selected').text(newtext).change();
return;
}
});
});
HTML
HTML
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2" data-icon="1">Friends</option>
<option value="3">Stackoverflow</option>
</select>
<br><br>
<button id="addok">Add <i class='fa fa-check'></i></button>
<button id="removeok">Remove <i class='fa fa-check'></i></button>
As you see, you can add or remove the icon in Hello
and Stackoverflow
items, but in Friends
(that is the option formated with formatSelection
and formatResult
), does not remove the icon, and if you try to add the icon, the appends another one to the existing.
如您所见,您可以在Hello
和Stackoverflow
项目中添加或删除图标,但在Friends
(即用formatSelection
和格式化的选项formatResult
)中,不会删除图标,如果您尝试添加图标,则会将另一个图标附加到现有图标。
Do you have any idea to solve this?
你有什么想法来解决这个问题吗?
采纳答案by harrison4
Simply replacing <
by <
in the option and removing format functions:
只需在选项中替换<
为<
并删除格式功能:
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2">Friends <i class='fa fa-check'></i></option>
<option value="3">Stackoverflow</option>
</select>
You can test it here: http://jsbin.com/nasixuro/11/edit
你可以在这里测试:http: //jsbin.com/nasixuro/11/edit
回答by Fares M.
I think there's two ways to achieve that:
我认为有两种方法可以实现:
The firstsolution is the better one,
you can make it work just by defining an escapeMarkupfunction in select2options, and this function must return the same data received as input parameter without any changes.
all what you need is:
$("#sel").select2({ escapeMarkup: function(m) { return m; } });
here's a working example: http://jsbin.com/nasixuro/3/edit
The secondone, make a small changes in select2.jsfile.
after inspecting the select2.js, i found the function which updates the text, and there was a little problem, select2.jsplugin escapes html to prevent js injection, so to get it work as you expect you have to avoid escaping html and use .html()function from jquery api to insert your html instead of .append()function used in updateSelectionfunction of select2.js.
here's the function i'm talking about:
// single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } },
delete this:
if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); }
and change:
if (formatted !== undefined) { container.append(formatted); }
to:
if (data !== undefined) { container.html(data.text); }
this is a dirty solution in my opinion.
For the Removeaction use this jscode:
$("#removeok").click(function() { actual_value= $("#sel").find(':selected').text(), indexOk =actual_value.indexOf(" <i class='fa fa-check'></i>"); if (indexOk > -1){ newtext =actual_value.substring(0, indexOk); $("#sel").find(':selected').text(newtext).change(); return; } });
第一个解决方案更好,
您可以通过在select2选项中定义一个转义标记函数 来使其工作,并且该函数必须返回作为输入参数接收的相同数据而无需任何更改。
您只需要:
$("#sel").select2({ escapeMarkup: function(m) { return m; } });
这是一个工作示例:http: //jsbin.com/nasixuro/3/edit
在第二一个,做一个小的变化select2.js文件。
在检查select2.js 后,我发现了更新文本的函数,但有一个小问题,select2.js插件会转义 html 以防止 js 注入,因此要使其按预期工作,您必须避免转义 html 并使用.html()函数从 jquery api 插入您的 html 而不是.append()函数在 select2.js 的updateSelection函数中使用。
这是我正在谈论的功能:
// single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } },
删除这个:
if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); }
并改变:
if (formatted !== undefined) { container.append(formatted); }
到:
if (data !== undefined) { container.html(data.text); }
在我看来,这是一个肮脏的解决方案。
对于Remove操作,请使用以下js代码:
$("#removeok").click(function() { actual_value= $("#sel").find(':selected').text(), indexOk =actual_value.indexOf(" <i class='fa fa-check'></i>"); if (indexOk > -1){ newtext =actual_value.substring(0, indexOk); $("#sel").find(':selected').text(newtext).change(); return; } });
回答by holmes2136
Manbe you can use the select2 parameter : formatResult or formatSelection like below
您可以使用 select2 参数:formatResult 或 formatSelection,如下所示
$(document).ready(function () {
$("#sel").select2();
$("#addok").click(function() {
$("#sel").select2({
//formatResult: format
formatSelection: format
//escapeMarkup: function(m) { return m; }
});
});
});
function format(state) {
if (!state.id) return state.text;
return "<i class='fa fa-check'></i>" + state.text;
}
回答by Mudassir Ali
You need not do the DOM manipulation manually
您无需手动进行 DOM 操作
var icon_checked = "<i class='fa fa-check'></i>";
function format(opt) {
var selection = this.element.select2("val");
if (opt.id === selection) {
return opt.text + icon_checked;
}
return opt.text;
}
$("#sel").select2({
formatResult: format
});
Basically this.element
returns you the select
element instance, on which you can run .select2("val")
to get the selected value.
基本上this.element
返回select
元素实例,您可以在该实例上运行.select2("val")
以获取所选值。
Compare that with the id of the object, if it is true
then give the HTML with checkbox else return plain text. I think this is what you were trying to achieve.
将其与对象的 id 进行比较,如果是,true
则使用复选框提供 HTML,否则返回纯文本。我认为这就是你想要达到的目标。
Here is a Working fiddle, I think this is what you were trying to acheive
这是一个工作小提琴,我认为这就是你想要达到的
回答by Artem Gorlachev
You can`t add tags inside option. Try to set option font as font-family: "myfontawesome", arial; and add special character instead css replacement.
您不能在选项中添加标签。尝试将选项字体设置为 font-family: "myfontawesome", arial; 并添加特殊字符而不是 css 替换。
回答by Mayank Bothra
Replace this code
替换此代码
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2" data-icon="1">Friends</option>
<option value="3">Stackoverflow</option>
</select>
and put this code
并把这个代码
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2">Friends</option>
<option value="3">Stackoverflow</option>
</select>
回答by Hoang Vuong
I changed a little code to check your data-icon
我更改了一些代码来检查您的数据图标
$("#addok").click(function() {
actual_value = $("#sel").find(':selected').text();
if($("#sel").find(':selected').data('icon') == '1')
{
alert("asd");
return}
Set data-icon = 0 to prevent it generate icon from format_select2_icon and remove icon.
设置 data-icon = 0 以防止它从 format_select2_icon 生成图标并删除图标。
if($("#sel").find(':selected').data('icon') == '1') {
$("#sel").find(':selected').data('icon','0') ;
$(".select2-chosen").text(actual_value).change();
}
See: http://jsbin.com/nasixuro/18/edit
见:http: //jsbin.com/nasixuro/18/edit
Hope that helped for you.
希望对你有帮助。
回答by Bene
If you want the icon to display, you need to target the HTML element and insert HTML not TEXT. pretty much like this:
如果要显示图标,则需要定位 HTML 元素并插入 HTML 而不是 TEXT。非常像这样:
$(document).ready(function () {
$("#sel").select2();
$("#addok").click(function() {
actual_value = $("#sel").find(':selected').text();
if (actual_value.indexOf(" <i class='fa fa-check'></i>") > -1){
alert("asd")
return
}
newtext = actual_value + "<i class='fa fa-check'></i>";
$("#s2id_sel").find('.select2-chosen').html(newtext);
});
});
See http://jsfiddle.net/S9tE3/
BUT. The HTML element you need to target, from what i can see, is $('s2id_'+[current element id]). s2 i guess for SELECT2 and id_. So your select is id="sel", which means $('s2id_sel')
. Also note that you need to find which one is chosen. It, conveniently enough, has a ".select2-chosen" class which makes it kinda easy to target.
但。从我所见,您需要定位的 HTML 元素是 $(' s2id_'+[ current element id])。s2 我猜是 SELECT2 和 id_。所以你的选择是 id="sel",这意味着$('s2id_sel')
. 另请注意,您需要找到选择了哪一个。它,足够方便,有一个“.select2-chosen”类,这使它很容易定位。
This won't change the value, just the LOOKwhich is I think what you're exactly trying to do.
这不会改变价值,只是我认为你正在尝试做的 LOOK。
Hope that helps
希望有帮助
回答by deweyredman
I think your problem is that you can't style values or add html to items that are in dropdown selects like you are trying to...it's pure text.
我认为您的问题是您无法设置样式值或将 html 添加到下拉选择中的项目中,就像您试图...它是纯文本。
newtext = actual_value + "wat";
See how your fiddle works when I remove the html and just add plaintext:
当我删除 html 并添加纯文本时,看看你的小提琴是如何工作的:
I also might suggest looking here.
我也可能建议看这里。
回答by Meloman
With fontawesome icon, you can use the following :
使用fontawesome icon,您可以使用以下内容:
.select2-results__option[aria-selected=true]::before {
content: "\f0c9";
font: normal normal normal 14px/1 FontAwesome;
color: rbg(255,0,0);
}
There is text-equivalent of each icon : http://fortawesome.github.io/Font-Awesome/cheatsheet/
每个图标都有文本等效项:http: //fortawesome.github.io/Font-Awesome/cheatsheet/
Or if you have gif for example, it works very well simply with your image as CSS backgroundlike this :
或者,例如,如果您有 gif,它可以很好地将您的图像用作 CSS 背景,如下所示:
.select2-results__option[aria-selected=true] {
background: url('path/to/image.gif') no-repeat 10px 10px;
}
Here is the result :
结果如下: