使用javascript/jQuery ..在选择列表中对选项进行排序,但按字母顺序排序
问题描述:
我正在寻找一个功能,该功能将选择列表中的选项列表并按字母顺序对它们进行排序,但要稍加改动.所有带有文本"NA"的值都应推到列表的底部.
I am looking for a function that will take a list of options in a select list and sort them alphabetically but with a twist. All values with the text 'NA' should be pushed to the bottom of the list.
因此给出了一个列表-
<select>
<option value="1">Car</option>
<option value="2">Bus</option>
<option value="3">NA</option>
<option value="4">Bike</option>
<option value="5">Tractor</option>
<option value="6">NA</option>
</select>
我们应该以-
<select>
<option value="4">Bike</option>
<option value="2">Bus</option>
<option value="1">Car</option>
<option value="5">Tractor</option>
<option value="3">NA</option>
<option value="6">NA</option>
</select>
NA的顺序并不重要.
The order of the NAs is not important.
不要问为什么我不能只删除NA(或者为什么会有多个选项具有相同的文本但具有不同的基础值,因为我也不同意.
And don't ask why I cannot just remove the NAs (or why there will be several options with the same texts but different underlying values, because I don't agree with it either.
答
演示: http://jsfiddle.net/4bvVz/
function NASort(a, b) {
if (a.innerHTML == 'NA') {
return 1;
}
else if (b.innerHTML == 'NA') {
return -1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
$('select option').sort(NASort).appendTo('select');