我有一个选择列表
<select id="select_zone">
<option value="north">North</option>
<option value="east">East</option>
<option value="south">South</option>
<option value="west">West</option>
</select>
现在我希望列表中的项目使用 jquery 以排序的方式出现。我应该能够手动(以随机顺序)在 html 代码的列表中添加项目。但是它们应该按字母顺序出现在浏览器页面中。
我一直在破脑袋,做了很多研发。但是无法找到在加载页面时对 dropdpwnlist 进行排序的方法。 请帮忙!
最佳答案
这是一个使用以下代码的工作 fiddle : http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/
代码:
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);
});
}
关于javascript - 如何显示带有排序下拉列表的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040915/