【问题标题】:Use jQuery to sort Select field使用 jQuery 对 Select 字段进行排序
【发布时间】:2014-04-12 02:14:21
【问题描述】:

我有一个选择字段,我需要将选项分组,但不是按升序或降序值。

我有游戏平台和游戏类型,我想在同一个下拉选择字段中将它们分成两组。

现在选择字段中的所有元素都按字母顺序排列,如下所示:

3DS
Action
Android
Beat 'Em Up
First Person Shooter
iOS

我想先用类型对它们进行排序,然后是这样的平台:

Action
Beat 'Em Up
First Person Shooter
3DS
Android
iOS

每个选项都有一个可以用来识别它的数值,但是如何更改它在选择字段中的位置/顺序?

$("select#cat option[value='45']");

谢谢! :D

【问题讨论】:

  • 您从哪里获取这些值?是 SQL 查询吗?

标签: jquery forms sorting select input


【解决方案1】:

http://jsfiddle.net/UqNrN/ HTML

<select id="test">
    <option value="4">3DS</option>
<option value="1">Action</option>
<option value="5">Android</option>
<option value="2">Beat 'Em Up</option>
<option value="3">First Person Shooter</option>
<option value="6">iOS</option>
</select>

JS

$(function(){
    $('#test').find('option').detach().sort(function(a, b){
        return a.value - b.value;
    }).appendTo('#test').parent().val('1');
});

【讨论】:

    【解决方案2】:

    您可以使用这种方式排序的选项重建选择:

    $(function(){
        var valueOrder = [46, 33, 21, 54, ...]//Specify the values order here
            opts = "";
    
        $.each(valueOrder, function (index, value) {
            opts += $("select#cat option[value='" + value + "']").get(0).outerHTML;//Get the option html
        });
    
        $("select#cat").html(opts);//build select with ordered options html
    });
    

    【讨论】:

      【解决方案3】:

      您可以通过使用多个选择框来完成此操作。

      var games = [
          {
              "name": "iOS and Android Game",
              "categories": ["ios", "android"]
          },
          {
              "name":"a 3ds game",
              "categories": ["3ds"]
          },
          {
              "name":"an action game",
              "categories": ["action"]
          }
      ]
      
      $("#categories").on("change", function(){
          var that = $(this);
          $("#games").empty();
          $.each(games, function(index, value){
              if (value["categories"].indexOf(that.val()) === -1) return;
              $("#games").append("<option>" + value["name"] + "</option>");
          })
      })
      

      Here is a fiddle.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 2012-12-09
        • 1970-01-01
        • 1970-01-01
        • 2012-10-30
        相关资源
        最近更新 更多