【问题标题】:How do you sort an HTML drop down by the Option text, not the value?如何按选项文本而不是值对 HTML 下拉列表进行排序?
【发布时间】:2014-04-15 04:23:09
【问题描述】:

当用户单击按钮时,我正在使用 jquery 将额外的流派加载到 HTML 下拉列表中。我想按选项文本的字母顺序排列下拉菜单,而不是值。

我的 php 类型数组看起来像

$genres = array (0=>"All", 200=>"Pop", 201=>"Classic Rock", ...etc

键编号作为下拉列表中的值加载,而文本填充选项。

还有我的 jquery

$.each(json, function(val, text)
{                   
    options[options.length] = new Option(text,val);
});

显示在下拉菜单中

All
Pop
Classic Rock

不按字母顺序排列

我的第一个计划是在php中对数组进行排序,但在测试时,即使数组是

 $genres = array (0=>"All", 201=>"Classic Rock", 200=>"Pop", ...etc

下拉菜单仍然显示

All
Pop
Classic Rock

如何强制它按照接收到 json 的顺序对其进行排序?

感谢您的帮助。

【问题讨论】:

  • 你能添加一个你的json的例子吗?

标签: php jquery arrays sorting drop-down-menu


【解决方案1】:

试试看,

$(function(){
    var options = $("#select-box-id option");
    options.sort(function(a,b) {
        if (a.text > b.text) return 1; // .text for text comparison
        else if (a.text < b.text) return -1;
        else return 0
    });
    $("#select-box-id").html(options );
});

Live Demo

【讨论】:

  • 我现在就试试这个罗汉。干杯。
  • 我忘了提到你的代码运行得非常好,Rohan - 干杯!
【解决方案2】:

如果在服务器端进行排序会更好(或者我觉得)。

PHP 有几种方法可以让您根据 KEY - (ksort)value - (asort) 进行排序

您可以对您的数组执行此操作:-

$genres = array (0=>"All", 200=>"Pop", 201=>"Classic Rock", ...etc
$stortedgeneres=$genres;
asort($stortedgeneres);

然后你可以在这个数组 ($sortedgeneres) 上使用你的 JavaScript 来像以前一样循环。

参考资料:- http://www.w3schools.com/php/php_arrays_sort.asp

【讨论】:

  • 谢谢。我也是这么想的,但是即使在服务器端按选项文本排序,jquery 似乎也是根据键值构建下拉列表。
猜你喜欢
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 2015-02-14
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多