我正在使用select2.js VERSION 4.0来显示带有标记的精彩下拉列表:
Html:
<select style="width: 300px">
<optgroup label="Europe">
<option value="cz" > Tcheque</option>
<option value="al" > Albania</option>
<option value="mt" > Malte</option>
<option value="mc" > Monaco</option>
<option value="ro" > Romania</option>
</optgroup>
<optgroup label="Africa">
<option value="dz">Algeria</option>
<option value="ml">Mali</option>
<option value="ma">Marocco</option>
</optgroup>
</select>
使用Javascript:
function formatResult(item) {
if(!item.id) {
// return `text` for optgroup
return item.text;
}
// return item template
var my_class = "flag flag-" + item.id;
return '<i>' + item.text + ' <img src="~/Content/images/blank.gif" class="' + my_class + '" alt="dzdz" /></i>';
}
function formatSelection(item) {
// return selection template
return '<b>' + item.text + '</b>';
}
$('select').select2({
formatResult: formatResult,
formatSelection: formatSelection
});
它呈现我想要的东西:
但是我想用本地源代码来做这样的javascript数据:
var datasource = [
{"id":"cz","text":"Tcheque"},
{"id":"al","text":"Albania"},
{"id":"mt","text":"Malte"},
{"id":"mc","text":"Monaco"},
{"id":"ro","text":"Romania"}
]
$('select').select2({
data:datasource ,
formatResult: formatResult,
formatSelection: formatSelection
});
你知道怎么做吗?