Sorting/reorganising select 选项列表 Javascript

Sorting/reorganising a select option list in Javascript

我有一个 Select 选项列表,其中的水果顺序是随机的,有些上面标有“缺货”标签。我想要做的是按字母顺序对它们进行排序,然后将“缺货”标签从口味的开头移动到口味的结尾,这样它们就会显示为:“柠檬 - 缺货”而不是它的显示方式当前是:“缺货 - 柠檬”。到目前为止,我在以下位置寻找“缺货”标签,然后将其添加到末尾,但不确定如何从一开始就将其删除,或者是否有更好的方法来实现我想做。

document.querySelectorAll('.form-dropdown').forEach(function(select) {
  Array.from(select.options).forEach(function(option) {
    if (option.innerText.includes("Out of stock")) {
      select.insertBefore(option, select.options[1]);
      option.innerText += (' - Out of stock');
    }
  });

  var cl = document.querySelector('.form-dropdown');
  var clTexts = new Array();
  for (i = 1; i < cl.length; i++) {
    clTexts[i - 1] =
      cl.options[i].text.toUpperCase() + "," +
      cl.options[i].text + "," +
      cl.options[i].value;
  }
  clTexts.sort();
  for (i = 1; i < cl.length; i++) {
    var parts = clTexts[i - 1].split(',');
    cl.options[i].text = parts[1];
    cl.options[i].value = parts[2];
  }
});
<select class="form-dropdown">
  <option disabled="" value="">Choose option</option>
  <option value="6">Watermelon</option>
  <option value="2">Out of stock - Cherry</option>
  <option value="3">Kiwi</option>
  <option value="0">Apple</option>
  <option value="4">Out of stock - Lemon</option>
  <option value="1">Banana</option>
  <option value="5">Out of stock - Melon </option>
  <option value="4">Out of stock - Pineapple</option>
  <option value="1">Strawberry</option>
  <option value="5">Out of stock - Khaki</option>
</select>

您可以在排序中使用一个函数,在该函数中您将按某种条件对字符串进行排序,在本例中为字母顺序。它使用 localCompare() 内置方法来执行此操作。

看看:

const pattern = " - "
const chooseText = "Choose option"
const select = document.querySelector(".form-dropdown")

const children  = [...select.children]

// brings "Out of stock" to the end
children.forEach(child => child.textContent = child.textContent.split(pattern).reverse().join(pattern))

children.sort(compareChild)

function compareChild(a, b){
    const str_a = a.textContent
    const str_b = b.textContent
    // remember to not consider disabled option while sorting
    if(str_a === chooseText || str_b === chooseText) return 0;
    return str_a.localeCompare(str_b)
}

select.replaceChildren(...children)
<select class="form-dropdown">
  <option disabled="" value="">Choose option</option>
  <option value="6">Watermelon</option>
  <option value="2">Out of stock - Cherry</option>
  <option value="3">Kiwi</option>
  <option value="0">Apple</option>
  <option value="4">Out of stock - Lemon</option>
  <option value="1">Banana</option>
  <option value="5">Out of stock - Melon</option>
  <option value="4">Out of stock - Pineapple</option>
  <option value="1">Strawberry</option>
  <option value="5">Out of stock - Khaki</option>
</select>