我正在尝试按选择框中的值对选项进行排序。使用下面的代码排序很好。但我有选项值null,它会到达底部,应该在顶部。
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = parseInt($(a).attr('value'), 10);
var brel = parseInt($(b).attr('value'), 10);
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
来源:Sorting Select box with jQuery
实际结果:
<select name="option[285]">
<option value="298">Blazing Yellow</option>
<option value="299">Jet Black</option>
<option value="300">Tabacco Brown</option>
<option value="301">Optical White</option>
<option value="302">Fiery Red </option>
<option value="" selected="selected"> --- Please Select --- </option>
</select>
预期结果:
<select name="option[285]">
<option value="" selected="selected"> --- Please Select --- </option>
<option value="298">Blazing Yellow</option>
<option value="299">Jet Black</option>
<option value="300">Tabacco Brown</option>
<option value="301">Optical White</option>
<option value="302">Fiery Red </option>
</select>
答案 0 :(得分:3)
问题似乎是parseInt('')
给定NaN
,使用arel < brel
进行比较会得出错误的结果
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = parseInt($(a).attr('value'), 10) || 0;
var brel = parseInt($(b).attr('value'), 10)|| 0;
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
演示:Fiddle