我有一个使用数据库中的数据填充的html选择。查询基于显示顺序(DB中的另一个字段)进行排序。
返回的数据:id,name
示例:{"1":"First","11":"Second","10":"Third"}
当添加到select时,排序基于id,如下所示:
First
Third
Second
如何在将数据添加到选择时保持数据的排序?
答案 0 :(得分:0)
一个选项是将json对象转换为数组(每个属性都是数组中的元素),然后按名称对数组进行排序,并将其附加到select:
var json = {"1":"First","11":"Second","10":"Third"};
var list = new Array();
// insert all the properties and their values into an array of objects
for(var propName in json) {
list.push({ "id": propName, "value":json[propName] });
}
// sort the array using the value instead of the id
list.sort(function compare(a,b) {
if (a.value < b.value)
return -1;
else
return 1; // we consider that if they have the same name, the first one goes first
});
// append the options in order in the select
for (var x = 0; x < list.length; x++) {
$("#mySelect").append("<option value='" + list[x].id + "'>" + list[x].value + "</option>");
}
答案 1 :(得分:0)
我通过更改返回的数据格式修复了此问题,因此它包含显示顺序以及ID和名称:
例如:[{&#34; id&#34;:&#34; 4&#34;,&#34; name&#34;:&#34; Name One&#34;,&#34; display_order&# 34;:&#34; 1&#34;},{&#34; id&#34;:&#34; 2&#34;,&#34; name&#34;:&#34; Name Two&#34; &#34; display_order&#34;:&#34; 2&#34;}]