我正在学习 Javascript/JQuery,并且我从教程中拼凑了一些代码,用于按字母顺序对 HTML 列表进行 A - Z 排序。
我的代码似乎工作正常。
但现在我必须按字母顺序从 A-Z 对整个列表进行排序(最后一个值除外)。
我不知道如何对除最后一个值之外的所有值进行排序。我搜索了SO和Google,但仍然无法弄清楚。
这是我的代码:
function sortCurrentSectorTypes() {
// sort the sector types list in alphabetical order (A-Z) after language code has changed.
var selected = $("#id_current_sector_type").val(); // preserve the users selected value.
var options = $('#id_current_sector_type option');
var arr = options.map(function(_, o) {
return {t: $(o).text(), v: o.value};
}).get();
arr.sort(function(o1, o2) {
return o1.t.toLowerCase() > o2.t.toLowerCase() ? 1 : o1.t.toLowerCase() < o2.t.toLowerCase() ? -1 : 0;
});
options.each(function(i, o) {
console.log(i);
o.value = arr[i].v;
$(o).text(arr[i].t);
});
$("#id_current_sector_type").val(selected); // assign the preserved users selected value.
}
最佳答案
由于您使用的是 jQuery,因此您可以使用 :not
和 :last
选择器:
var $elements = $(".someClass:not(:last)");
关于javascript - 循环遍历除最后一个值之外的 html 选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27885164/