javascript - 循环遍历除最后一个值之外的 html 选择列表

标签 javascript sorting

我正在学习 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/

相关文章:

javascript - 如何在 JavaScript 中将 "range"的值转换为 float ?

javascript - jquery/javascript 从字符串声明变量

javascript - React CPU 使用率(快速更新)

linux - linux sort 的奇怪行为

mysql - 如何找到相似的结果并按相似度排序?

javascript - 返回 defer 本身和返回 defer.promise 的区别

Javascript 数组拼接无法正常工作

javascript - Jquery UI 可排序更改无法正常工作

c++ - 使用 STL 按列对二维数组进行排序

java - Java中按字符对字符串列表进行排序