如何显示具有排序下拉列表的页面? [英] How to display a page with a sorted drop down list?
问题描述
我有一个选择列表
< 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进行排序的方法。
请帮助!
这是一个使用代码的工作小提琴:
http://sebastienayotte.wordpress.com/2009/08/04 / sorting-drop-down-list-with-jquery /
code:
函数sortDropDownListByText(){
//循环页面上的每个select元素。
$(select)。each(function(){
//跟踪选定的选项
var selectedValue = $(this).val();
//通过文本排序所有选项我可以通过val。
$(this).html($(option,$(this))sort。函数(a,b){
返回a.text == b.text?0:a.text< b.text?-1:1
}));
//选择一个选项
$(this).val(selectedValue);
});
}
I have a select list
<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>
Now I want the items in the list to appear in a sorted manner using jquery. I should be able to add items in the list in the html code manually (in a random order). BUT they should appear alphabetically sorted in the browser page.
I have been breaking my head and have done a lot of R&D. But not being able to find a way to sort the dropdpwnlist at the time the page is loaded. Please help!
here is a working fiddle using code from : http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/
code:
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);
});
}
这篇关于如何显示具有排序下拉列表的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!