我有一个选择字段,我需要将选项分组,但不能按升序或降序排序。
我有游戏平台和游戏类型,我想在同一个下拉选择栏中将它们分成两组。
现在所有元素在选择字段中都是按字母顺序排列的,如下所示:
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
答案 0 :(得分:0)
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');
});
答案 1 :(得分:0)
您可以使用以这种方式订购的选项重建选择:
$(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
});
答案 2 :(得分:0)
您可以使用多个选择框来完成此操作。
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>");
})
})