4

我试图将图标放在类似于 GitHub 中的标志示例的选项旁边:http: //ivaynberg.github.io/select2/#templating,但需要图标基于它们所在的 optgroup。我每次选择都以相同的图标结束,而不仅仅是在他们的 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>  
4

1 回答 1

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;
      }
于 2013-06-15T00:00:09.947 回答