繁体   English   中英

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

[英]Adding options to a select using jQuery - changing the order

我编写了以下代码来填充Jquery中的列表框(基于什么是使用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的顺序排序-即 倒序列出

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

.append()更改为.prepend()

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

工作演示

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

改进的代码如下所示:

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM