问题
I am trying to display fontawesome icons in the Select2 v4 dropdown items. But the dropdown is displaying the html and not generating the actual icon. This method works with select2 V3 but does not seem to with v4. Any help is appreciated. Thank you
HTML
<div class="select2-wrapper">
<select class="input icons_select2">
<option value="fa-dribbble" data-icon="fa-dribbble">Dribbble</option>
<option value="fa-dropbox" data-icon="fa-dropbox">Dropbox</option>
<option value="fa-facebook" data-icon="fa-facebook">Facebook</option>
</select>
</div>
JS
function iformat(icon) {
var originalOption = icon.element;
return '<i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text;
}
$('.icons_select2').select2({
width: "100%",
templateSelection: iformat,
templateResult: iformat
});
See the fiddle for an example: http://jsfiddle.net/qCn6p/206/
回答1:
Here is your updated fiddle
You have to wrap your element inside of jquery like this:
function iformat(icon) {
var originalOption = icon.element;
return $('<span><i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text + '</span>');
}
$('.icons_select2').select2({
width: "100%",
templateSelection: iformat,
templateResult: iformat,
allowHtml: true
});
回答2:
Use the "escapeMarkup" option as follow
$('.icons_select2').select2({
width: "100%",
templateSelection: iformat,
templateResult: iformat,
escapeMarkup: function(m) {
return m;
}
});
http://jsfiddle.net/qCn6p/209/
回答3:
You can wrap the return with $.parseHTML()
.
Example: return $.parseHTML('<i class="fa ' + $(originalOption).data('icon') + '"></i> ' + icon.text);
回答4:
FYI if you return a string for the templateSelection/templateResult overridden functions, it will be escaped (unless you also override the escapeMarkup function), however if you return a jquery object it will NOT be escaped.
Some examples also disregard formatting input without and id
if (!icon.id) { return icon.text; }
See this Fiddle http://jsfiddle.net/dleffler/15myta6t/3/
来源:https://stackoverflow.com/questions/41981532/add-fontawesome-icons-into-select2-v4-dropdown-items