按字母顺序排序下拉条目

时间:2011-02-18 09:03:51

标签: javascript html

我使用以下代码动态地将drop条目添加到下拉列表中。

var x =document.getElementById("x");
var optn = document.createElement("OPTION");
optn.text="hhh";  
optn.value="val";  
x.add(optn);  

上面的事情是循环完成的 现在我想按字母顺序排序。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

在将选项添加到下拉列表之前,sort the array会更容易。添加DOM元素一旦被添加就会效率降低。例如:

var arr = [ { id: '1', value: 'B' },
            { id: '2', value: 'A' },
            { id: '3', value: 'C' } ];
arr.sort(function(a, b) {
    if (a.value < b.value) {
        return -1;
    }
    if (a.value > b.value) {
        return 1;
    }
    return 0;
});

for (var i = 0; i < arr.length; i++) {
    // TODO: the array is now sorted => build the dropdown here
}

答案 1 :(得分:-1)

public void SortDropDownList(DropDownList ddl)
{
    //create a ListItem array the size of the items
    //in your DropDownList
    ListItem[] sorted = new ListItem[ddl.Items.Count];
    //loop through all the items in your ListItem array
    for (int i = 0; i < sorted.Length; i++)
    {
        //resize the array on each iteration
        Array.Resize(ref sorted, i);
        //add the current index to the array
        sorted[i] = ddl.Items[i];
    }
    //call Array.Sort to sort your ListItem array
    Array.Sort(sorted);
    //remove all items from the DropDownList
    ddl.Items.Clear();
    //add the sorted items to the DropDownList
    ddl.Items.AddRange(sorted);
}

在绑定到下拉列表的所有项目之后使用此功能的帮助