如何显示带有排序下拉列表的页面?

我有一个选择列表

 North East South West  

现在我希望列表中的项目使用jquery以排序的方式显示。 我应该能够手动(以随机顺序)在html代码中的列表中添加项目。 但它们应按字母顺序排列在浏览器页面中。

我一直在打破我的头脑并做了很多研发。 但是无法在加载页面时找到对dropdpwnlist进行排序的方法。 请帮忙!

这是一个使用代码的工作小提琴: http : //sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/

http://jsfiddle.net/Rz6xv/

码:

 function sortDropDownListByText() { // Loop for each select element on the page. $("select").each(function() { // Keep track of the selected option. var selectedValue = $(this).val(); // Sort all the options by text. I could easily sort these by val. $(this).html($("option", $(this)).sort(function(a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 })); // Select one option. $(this).val(selectedValue); }); } 

写一个方法并调用文件就绪()

 function sortMycombo() { $("#select_zone").html($('#select_zone option').sort(function(x, y) { return $(x).text() < $(y).text() ? -1 : 1; })) $("#select_zone").get(0).selectedIndex = 0; e.preventDefault(); }); 

你可以使用jQuery和类似的东西:

 $("#id").html($("#id option").sort(function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 }))