我创建了select2下拉列表。现在我想按国家名称在此下拉列表中添加说明,城市,商店等。 如何添加国家城市名称,地区,商店等?
(function($) {
$(function() {
var isoCountries = [
{ id: 'QA', text: 'Qatar',},
{ id: 'CA', text: 'Canada'},
{ id: 'CN', text: 'China'},
{ id: 'DE', text: 'Germany'},
{ id: 'RU', text: 'Russia'},
{ id: 'IT', text: 'Italy'}
];
$("[name='market']").select2({
placeholder: "Select a country",
data: isoCountries
});
});
})(jQuery);
答案 0 :(得分:0)
检查以下代码:
(function($) {
var isoCountries = [
{ id: 'US', text: 'USA', description: 'New York'},
{ id: 'SP', text: 'Spain', description: 'Barcelona'}
];
$("[name='market']").select2({
placeholder: "Select a country",
data: isoCountries,
templateResult: function(data){
return $('<span>')
.html(data.text + ' - ')
.append($('<i>')
.html(data.description));
},
templateSelection: function(data){
return $('<span>')
.html(data.text + ' - ')
.append($('<i>')
.html(data.description));
}
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select name="market" style="width:100%;"></select>
仅适用于select2版本4 +。如果您想将其与以前的版本一起使用而不是usisng templateResult和templateSelection,请使用formatResult和formatSelection。