循环浏览除最后一个值之外的html选择列表

时间:2015-01-11 08:08:45

标签: javascript sorting

我正在学习Javascript / JQuery,我从教程中拼凑了一些代码,按字母顺序从A - Z中对HTML列表进行排序。

我的代码似乎工作正常。

但是现在我必须按照字母顺序对A-Z中的整个列表进行排序,除了最后一个值。

我无法弄清楚如何对除了最后一个值之外的所有值进行排序。我搜索了SO和谷歌,但仍然无法弄明白。

这是我的代码:

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.

}

2 个答案:

答案 0 :(得分:2)

由于您使用的是jQuery,因此可以使用:not:last选择器:

var $elements = $(".someClass:not(:last)");

答案 1 :(得分:0)

我认为你太复杂了。只需删除最后一个元素,并在完成后将其放回去。

排序前

var lastEl = options.pop();
排序后

options.push(lastEl);

现在最后一个元素没有被排序,它仍然在最后。

相关问题