循环选择器选项

Looping through selectpicker options

我正在使用一个包含 optgroup 和 option 元素的 selectpicker。我想遍历选项和“select”所有具有以特定字符串开头的值的选项。例如,如果我有以下内容:

<select id="sp" class="form-control selectpicker" data-live-search="true" data-live-search-style="startsWith" multiple>
  <optgroup label='Vegetables'>
    <option value='V.celery'>Celery</option>
    <option value='V.carrot'>Carrot</option>
    <option value='V.artichoke'>Artichoke</option>
  </optgroup>
  <optgroup label='Fruits'>
    <option value='F.cherry'>Cherry</option>
    <option value='F.apple'>Apple</option>
    <option value='F.papaya'>Papaya</option>
  </optgroup>
</select>

还有一些按钮“蔬菜”和“水果”,我想要所有值以“V”开头的选项。当用户单击“蔬菜”按钮时 selected。我如何使用 selectpicker 'val' 选项来做到这一点?谢谢!

function selector() {
  if (this.id === "vegBtn") document.querySelectorAll("optgroup[label='Vegetables'] option").forEach(elem => {
    if (elem.value.indexOf("V.") !== -1) elem.selected = !elem.selected;
  });
  else if (this.id === "fruBtn") document.querySelectorAll("optgroup[label='Fruits'] option").forEach(elem => {
    if (elem.value.indexOf("F.") !== -1) elem.selected = !elem.selected;
  });
}

document.getElementById("vegBtn").addEventListener("click", selector);
document.getElementById("fruBtn").addEventListener("click", selector);
<select id="sp" class="form-control selectpicker" data-live-search="true" data-live-search-style="startsWith" multiple>
  <optgroup label='Vegetables'>
    <option value='V.celery'>Celery</option>
    <option value='V.carrot'>Carrot</option>
    <option value='V.artichoke'>Artichoke</option>
  </optgroup>
  <optgroup label='Fruits'>
    <option value='F.cherry'>Cherry</option>
    <option value='F.apple'>Apple</option>
    <option value='F.papaya'>Papaya</option>
  </optgroup>
</select>
<button id="vegBtn">
 Vegetables
</button>
<button id="fruBtn">
 Fruits
</button>

我不确定在这种情况下您是否真的需要 select 用于 V 或 F,但因为这是您的要求,所以我就是这样做的。两者并不相互排斥,因此如果您需要,则需要更多代码。