从下拉列表中的数组中选取某个项目,然后将其显示为第一项并按字母顺序显示

Picking a certain item from an array in a dropdown list then showing it as the first item and in alphabetic order.

本文关键字:显示 顺序 一项 选取 数组 下拉列表 然后 项目      更新时间:2023-09-26

我的下拉列表应该包含一个数组中所有项目的列表。但是,它们不应该从 A-Z 组织,但选择一个项目应该使其成为列表中的第一项,并且列表应该从那里按字母顺序继续。我怎样才能做到这一点?

在此处输入代码

var array =["cellphone", "camara", "computer", "mouse", "track-pad", "usb", "screen"] 
enter code here
<select id="dropdownList">
<option>cellphone</option>
<option>camara</option>
<option>computer</option>
<option>mouse</option>
<option>track-pad</option>
<option>usb</option>
<option>screen</option>
</select>

你可以做这样的事情:
检查下面的代码段

var array = ["cellphone", "camara", "computer", "mouse", "track-pad", "usb", "screen"];
var select = document.getElementById('dropdownList');
select.addEventListener('change', function() {
  array.sort(function(val1, val2) {
    return val1.localeCompare(val2);
  });
  array.unshift(this.value);
  array.splice(array.lastIndexOf(this.value), 1);
  var values = "";
  for (var i = 0; i < array.length; i++) {
    values += '<option>' + array[i] + '</option>';
  }
  select.innerHTML = values;
  console.log(array);
  console.log(this.value);
});
<select id="dropdownList">
  <option>cellphone</option>
  <option>camara</option>
  <option>computer</option>
  <option>mouse</option>
  <option>track-pad</option>
  <option>usb</option>
  <option>screen</option>
</select>

我写了几个jQuery插件,使这个任务变得简单,适用于任何选择框。这是最简洁的jQuery代码。这是最佳的,因为我们永远不会删除选项并创建新选项。相反,我们覆盖了它们的值。

(function($) {
  $.fn.populateSelect = function(items, valueField, displayField) {
    return this.append(items.map(function(item, index) {
      return $('<option>', {
        value : valueField   != null ? item[valueField]   : index,
        text  : displayField != null ? item[displayField] : item
      });
    }));
  };
  $.fn.selectedValue = function() {
    return this.find('option:selected').val();
  };
  $.fn.sortOptionsBy = function(key) {
    var options = this.find('option'), arr = options.map(function(_, opt) {
      return { text: opt.text, value: opt.value };
    }).get().sort(function(o1, o2) {
      return o1[key] > o2[key] ? 1 : o1[key] < o2[key] ? -1 : 0;
    });
    options.each(function(idx, opt) { $.extend(opt, arr[idx]); });
    return this;
  };
  $.fn.moveToIndex = function(val, idx) {
    this.find('option[value="' + val + '"]').insertBefore(this.find('option:eq(' + idx + ')'));
    return this.prop('selectedIndex', idx);
  };
  $.fn.moveSelectedToTop = function() {
    var selected = this.selectedValue();
    return this.sortOptionsBy('text').moveToIndex(selected, 0);
  }
}(jQuery));
var data = ["cellphone", "camera", "computer", "mouse", "track-pad", "usb", "screen"];
$('#dropdown-list').populateSelect(data).on('change', function(e, item) {
  $(e.target).moveSelectedToTop();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="dropdown-list"></select>