用jQuery排序选择框 [英] Sorting Select box with jQuery
本文介绍了用jQuery排序选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,可以通过.text()值将这些选项排序成字母顺序。
我的问题是,使用jQuery,我如何使用rel属性按升序排序?
< option rel =1value =ASHCHRC> Ashchurch for Tewkesbury< / option>
< option rel =2value =EVESHAM> Evesham< / option>
< option rel =3value =CHLTNHM> Cheltenham Spa< / option>
< option rel =4value =PERSHOR> Pershore< / option>
< option rel =5value =HONYBRN> Honeybourne< / option>
< option rel =6value =MINMARS> Moreton-in-Marsh< / option>
< option rel =7value =GLOSTER> Gloucester< / option>
< option rel =8value =GTMLVRN> Great Malvern< / option>
< option rel =9value =MLVRNLK> Malvern Link< / option>
我的排序函数:var object;可以是整个表单中的许多选择框之一。
$(object).each(function(){
//跟踪所选的选项
var selectedValue = $(this).val();
//排序出来
$(这) .html($(option,$(this))。sort(function(a,b){
return a.text == b.text?0:a.text< b.text?
$ b //选择一个选项
$(this).val(selectedValue);
});
解决方案
如果您要按rel排序,功能
$(this).html($(option,$(this))sort(function(a, b){
var arel = $(a).attr('rel');
var brel = $(b).attr('rel');
return arel == brel ?0:arel< brel?-1:1
}));
使用parseInt()编辑
return arel == brel?0:arel< brel ?-1:1
}));
I have a select box on a form, which carries an incremental rel attribute. I have a function that can sort the options by thier .text() value, into alphabetcal order.
My question is, with jQuery, how do i sort in an ascending order using the rel attribute ?
<option rel="1" value="ASHCHRC">Ashchurch for Tewkesbury </option>
<option rel="2" value="EVESHAM">Evesham </option>
<option rel="3" value="CHLTNHM">Cheltenham Spa </option>
<option rel="4" value="PERSHOR">Pershore </option>
<option rel="5" value="HONYBRN">Honeybourne </option>
<option rel="6" value="MINMARS">Moreton-in-Marsh </option>
<option rel="7" value="GLOSTER">Gloucester </option>
<option rel="8" value="GTMLVRN">Great Malvern </option>
<option rel="9" value="MLVRNLK">Malvern Link </option>
my sort function: var object; can be one of many select boxes throughout the form.
$(object).each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// sort it out
$(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);
});
解决方案
If you want to sort by rel you should change your function
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = $(a).attr('rel');
var brel = $(b).attr('rel');
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
edit with parseInt()
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = parseInt($(a).attr('rel'), 10);
var brel = parseInt($(b).attr('rel'), 10);
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
这篇关于用jQuery排序选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文