排序前后对比图
before:
after:
1 <select id="myselect" size="5"> 2 <option>E</option> 3 <option>D</option> 4 <option>C</option> 5 <option>A</option> 6 <option>B</option> 7 </select>
1 $(function () { 2 var options = {} 3 $('#myselect option').each(function () { 4 var option = $(this) 5 console.log(option) 6 options[option.text()] = option 7 setTimeout(() => { 8 console.log(option[0]) 9 }, 1000); 10 setTimeout(() => { 11 console.log(option.text()) 12 }, 2000); 13 })
将
1
|
console.log(Object.keys(options)) |
1
|
var keys = Object.keys(options).sort() |
2
|
console.log(keys) |
1 var keys = Object.keys(options).sort() 2 var $myselect = $('#myselect').empty() 3 $.each(keys,function(i,key){ 4 $myselect.append(options[key]) 5 })
将select清空,然后调用.each方法遍历keys数组,将之前保存的已经排序过的数组内容依次插入select中
引用文章:https://www.cnblogs.com/qiuchuanji/p/7737831.html