【问题标题】:Order HTML Select based on data orderOrder HTML 根据数据顺序选择
【发布时间】:2015-03-28 04:33:16
【问题描述】:

我有一个使用数据库中的数据填充的 html 选择。该查询基于显示顺序(数据库中的另一个字段)进行排序。

返回的数据:id、名称

示例:{"1":"First","11":"Second","10":"Third"}

添加到select时,根据id排序,如下:

First  
Third  
Second

将数据添加到选择时如何保持数据的顺序?

【问题讨论】:

    标签: html database select options


    【解决方案1】:

    我通过更改返回数据的格式解决了这个问题,使其包含显示顺序以及 id 和名称:

    例如:[{"id":"4","name":"Name One","display_order":"1"},{"id":"2","name":"Name Two" ,"display_order":"2"}]

    【讨论】:

      【解决方案2】:

      一种选择是将 json 对象转换为数组(每个属性都将是数组中的一个元素),然后按名称对数组进行排序,并将其附加到选择中:

      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>");
      }
      

      您可以see it working on this jsfiddle

      【讨论】:

      • 谢谢阿尔瓦罗。您假设“值”是您要排序的内容。我最初的问题是要根据 JSON 数组中项目的顺序来选择排序。
      • 您想要的可能无法实现,因为 JavaScript 不保证对象中的属性顺序(请参阅此问题:stackoverflow.com/questions/5525795/…)。
      • 解决方案是返回具有不同结构并包括顺序(如果可能)的值。你必须从你所拥有的{"1":"First", "2":"Second", ...}(这对我来说看起来很奇怪,但这可能只是我)变成更有条理的东西:[ { "id":"1", "value":"First", "order":1}, {"id":"2","value":"Second","order":3}, ... ]。一旦你有了这个结构,按照上面的解决方案,只需将 compare 函数从 a.value 和 b.value 更改为 a.order 和 b.order
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多