【问题标题】:how to sort select option in lexical order [duplicate]如何按词汇顺序对选择选项进行排序[重复]
【发布时间】:2014-05-29 12:12:31
【问题描述】:

我有一个选择选项

<select>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

如何对它们进行排序。 所以输出会

aaa
bbb
ccc
ddd

这个问题是在一次采访中问我的 如果有的话请回答提前知道谢谢

【问题讨论】:

  • 谢谢.......可能这是一个重复的问题,但我真的不知道答案

标签: javascript jquery html sorting


【解决方案1】:

您可以使用 JavaScript 排序方法。它按词汇顺序对元素进行排序。所以你可以根据排序函数的结果来设置select元素的innerHTML。

阅读更多关于排序功能here

试试:

$("select").html($('select option').sort(function (x, y) {

    return $(x).text() < $(y).text() ? -1 : 1;

}))

DEMO

【讨论】:

  • 你能给我解释一下吗
  • @mayankchaturvedi 更新答案
  • 如果有人有看起来像“20 人”、“5 人”的选项并希望对它们进行正确排序(“20”中的“2”将排在“5”之前),您可以使用return parseInt($(x).text().split(' ')[0]) &lt; parseInt($(y).text().split(' ')[0]) ? -1 : 1; 和“5 人”将排在“20 人”之前。
【解决方案2】:

添加一个ID

<select id='myselect'>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

获取数组中的所有选项,对其进行排序,然后更改选择的值

var array = new Array();
$("#myselect option").each(function() { array.push($(this).text()) });
array.sort();

$("#myselect option").each(function(index,elem) { $(this).html(array[index]) });

【讨论】:

    【解决方案3】:

    Working Fiddle

    $('#sort').click(function () {
    $('select').each(function () {
       var options = $(this).children('option');
        options.sort(function (optionA, optionB) {
            return optionA.value.localeCompare(optionB.value);
        });
        $(this).empty().append(options);
    });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多