Javascript 和 HTML 中 Select 列表的倒序

Reversing Order of Select List in Javascript & HTML

// Generate and append Base array from DB based on ID selected
function BasePopulation(id) {

    // Use previous query
    var array = dropdownRequest.responseJSON[id];
    
    // Create Base dropdown
    $("#inputGroup")
        .append(
            '<div class="col-12 col-sm-12 col-md-8 col-lg-8 col-xl-8 removable">' +
                '<select id="BaseSelect" name="BaseSelect" class="selectpicker" data-size="10" data-width="auto" data-container="body" title="Base">' +
                    '<option>Base</option>' +
                    '<!-- Populated in .js -->' +
                '</select>' +
            '</div>'
        );

    // Populate Base dropdown
    
    $.each(array, function(index, base) {
        // Reformat JD Base
        var base_value = BaseToValue(base);
    
        $("#BaseSelect")
            .append($("<option class='removable'></option>")
            .attr("value", base_value)
            .text(base));
    });
    
    $("#BaseSelect").selectpicker("refresh");
    
}

我正在尝试反转 HTML/Javascript 中下拉列表的顺序,但找不到反转功能。是否有执行此操作的功能,还是我必须手动执行此操作?

如果你扭转这个var array = dropdownRequest.responseJSON[id]; 具有 .reverse 函数的数组?

您可以通过两种方式反向填充下拉列表。

1: 与 jQuery .prepend() method instead of .append()

$.each(array, function(index, base) {
    // Reformat JD Base
    var base_value = BaseToValue(base);

    $("#BaseSelect")
        .prepend($("<option class='removable'></option>")  // Using prepend
        .attr("value", base_value)
        .text(base));
});

2: JS .reverse() 方法应用于数组

array.reverse()

$.each(array, function(index, base) {
  ...

阅读文档了解更多详情;)