我试图在选项旁边放置类似于GitHub中的标志示例的图标:http://ivaynberg.github.io/select2/#templating,但需要图标基于他们所在的optgroup。我最终得到了相同的图标通过每个选择,而不仅仅是在他们的选择组中。
JS
$(function() {
function format(ade) {
if (!ade.id)
return ade.text; // optgroup
return "<i class='icon-info'></i>" + ade.text;
}
function format(bob) {
if (!bob.id)
return bob.text; // optgroup
return "<i class='icon-user'></i>" + bob.text;
}
function format(jive) {
if (!jive.id)
return jive.text; // optgroup
return "<i class='icon-exchange'></i>" + jive.text;
}
$("#source").select2({
placeholder: "Get Started...",
allowClear: true,
minimumInputLength: 2,
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) {
return m;
}
});
});
HTML
<select id="source" class="search-box">
<option></option>
<optgroup label="Book of Business">
<option value="bob">Jasper Beardly</option>
<option value="bob">John Frink</option>
<option value="bob">Elizabeth Hoover</option>
<option value="bob">Edna Krabappel</option>
<option value="bob">Otto Mann</option>
</optgroup>
<optgroup label="Dashboard Content" id="ade">
<option value="ade">Additional time for Oklahoma customers to make payments</option>
<option value="ade">Who to call when you have California policy questions</option>
<option value="ade">Product Resource Center</option>
<option value="ade">Quote Tracker</option>
</optgroup>
<optgroup label="Community Discussions" id="jive">
<option value="jive">email account on Android phone</option>
<option value="jive">Problems with changing</option>
<option value="jive">Transfer discount for current client moving states </option>
<option value="jive">Quoting auto on existing client.</option>
<option value="jive">Where can I find sample ads/flyers/brochures for advertisement?</option>
</optgroup>
</select>
答案 0 :(得分:14)
老实说,这有点乱。
您有三个具有相同名称但具有不同参数名称的函数。那不行。删除三种格式的功能并将其替换为:
function format(o) {
if (!o.id)
return o.text; // optgroup
else if (o.id == 'bob')
return "<i class='icon-user'></i>" + o.text;
else if (o.id == 'ade')
return "<i class='icon-info'></i>" + o.text;
else
return "<i class='icon-exchange'></i>" + o.text;
}
更好的是,让您的类名与您的ID名称相匹配。所以
<option value="user">Jasper Beardly</option>
等
然后格式化函数变为:
function format(o) {
if (!o.id)
return o.text; // optgroup
else
return "<i class='icon-" + o.id + "'></i>" + o.text;
}