使用jQuery向选择添加选项 - 更改顺序

时间:2015-02-05 11:14:25

标签: javascript jquery

我编写了以下代码来填充Jquery中的列表框(基于What is the best way to add options to a select from an array with jQuery?

function populate(id, selectValues, theSelected, empty) {
    if (empty) {
        $(id).empty();
    }
    $.each(selectValues, function(key, value) {
        $(id).append($("<option></option>").attr("value", key)
             .prop('selected', key == theSelected).text(value));
    });
}

我使用例如调用函数以下代码

populate('#BASE1', {
    "8": "2012 average=100",
    "7": "2010 average=100",
    "6": "2008 average=100",
    "5": "2006 average=100",
    "4": "2002 average=100",
    "3": "2000 average=100",
    "2": "1998 average=100",
    "1": "1993 average=100"
}, selectedBase, true);

然而,该清单是按照ID的顺序排序的 - 即 List in reverse order

如何调整我的填充函数以按照我列出的顺序对它们进行排序? (显然我可以重新分配ID,但我想知道是否有其他解决方案)

2 个答案:

答案 0 :(得分:2)

.append()更改为.prepend()

$.each(selectValues, function(key, value) {
    $(id).prepend($("<option></option>").attr("value", key)
         .prop('selected', key == theSelected).text(value));
});

<强> Working Demo

答案 1 :(得分:2)

你不能依赖对象属性的顺序的问题,根本就没有为它们订购的东西。而是使用对象数组。

改进后的代码如下所示:

function populate(id, selectValues, theSelected, empty) {
    if (empty) {
        $(id).empty();
    }
    $.each(selectValues, function(i, obj) {
        $(id).append($("<option></option>").attr("value", obj.id)
             .prop('selected', obj.id == theSelected).text(obj.text));
    });
}

var selectedBase = 3;

populate('#BASE1', [
    {id: "8", text: "2012 average=100"},
    {id: "7", text: "2010 average=100"},
    {id: "6", text: "2008 average=100"},
    {id: "5", text: "2006 average=100"},
    {id: "4", text: "2002 average=100"},
    {id: "3", text: "2000 average=100"},
    {id: "2", text: "1998 average=100"},
    {id: "1", text: "1993 average=100"}
], selectedBase, true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="BASE1"></select>