繁体   English   中英

使用javascript对选择框中的选项重新排序

[英]Reorder the options in a select box with javascript

我有一个选择框,动态显示运输选项和价格列表。 我希望它们从最低价到最高价。

这是html的示例。

<select name="ShippingMethod">
  <option value="ups:1">UPS Next Day Air ($30.08)</option>
  <option value="ups:4">UPS 2nd Day Air ($14.77)</option>
  <option value="ups:6">UPS 3 Day Select ($10.93)</option>
  <option value="ups:7">UPS Ground ($8.00)</option>
  <option value="flatzonc:Pick up in store">Pick up in store ($0.00)</option>
  <option value="mvusps:PRIORITY">U.S.P.S. Priority Mail&reg; ($7.45)</option>
</select>

我知道如何将值放入数组中:

shippingOptions = [];
$('select[name=ShippingMethod] option').each(function() {
    myList.push($(this).html())
});

但就我而言。 我不知道如何使用它来排序它们并按顺序重新插入它们。 我是javascript的新手,所以我赞成帮助。

谢谢

http://jsfiddle.net/hPZ3F/17

// get all options
var shippingOptions = $('select[name=ShippingMethod] option');

// initialize sort
shippingOptions.sort(function(a,b) {
    // define regex that pulls contents of parens
    var patt = /\((.*)\)/;

    // for each element in sort, find the price and remove the dollar sign
    a.price = a.text.match(patt)[1].replace('\$', '');
    b.price = b.text.match(patt)[1].replace('\$', '');

    return a.price - b.price;
});

// update the select with the new option order
$('select[name=ShippingMethod]').append(shippingOptions);

// select the first option
$(shippingOptions[0]).attr("selected", "");

首先,您需要提取每个选项的$ amount,然后对这些选项进行排序并替换现有的下拉列表,这里是完整的代码:

http://jsfiddle.net/amyamy86/L8qgX/

// Get the price in the option
    var getPrice = function (str) {
        var price = 0;
        var result = str.match(/[0-9]+(.)[0-9]{2}/);    //regex matches >1 digit followed by . decimal, followed by 2 digits
        if (result.length > 0) {
            price = parseFloat(result[0]);
        }
        return price;
    };

// Sort the prices
    var sortPrices = function (priceList) {
        priceList.sort(function (a, b) {
            return a.price > b.price; // > is sort ascending order
        });
        return priceList;
    };

var prices = [];
// Get the option's label, value, price
    $('select[name=ShippingMethod] option').each(function () {
        var option = $(this);
        var price = getPrice(option.text());
        prices.push({
            label: option.html(),
            value: option.val(),
            price: price
        });
    });

var shippingOptions = sortPrices(prices);

// create output HTML
var output = '';
for (var i = 0; i < shippingOptions.length; i++) {
    output += '<option value="' + shippingOptions[i].value + '">' + shippingOptions[i].label + '</option>';
}

// replace <select> with sorted options
$('select[name="ShippingMethod"]').html(output);

您可以了解有关使用的更多信息

嗯,已经回答了,但我写了这封,所以无论如何我都会发帖,这几乎是其余所有这些的混合,大声笑..想想那个

$('select[name=ShippingMethod]').
    html($('select[name=ShippingMethod] option').
         clone().sort(function (a, b) {
            a = a.innerHTML, b = b.innerHTML;
            return parseFloat(
                    a.substr(a.indexOf('$') + 1)
                ) >= parseFloat(
                    b.substr(b.indexOf('$') + 1)
                );
        })
    );

http://jsfiddle.net/6zbzK/

编辑:在审核评论后,这是一个更有效但更详细的答案:

var selectOpts = $('select[name="ShippingMethod"] option');
var len = selectOpts.length;
var options = new Array(len), out = "", i;
selectOpts.each(function (index) {
    var self = $(this);
    var txt = self.text();
    options.push({
        'html': '<option value="' + self.val() + '">' + txt + '</option>',
        'price': parseFloat(txt.substr(txt.indexOf('$') + 1))
    });
    // Return if not last item
    if (index !== len - 1) {
        return;
    }
    // Sort options and set 'out'
    options.sort(function (a, b) {
        return a.price > b.price;
    });
    for (i = 0; i < len; i += 1) {
        out += options[i].html;
    };
}).parent('select').html(out);

http://jsfiddle.net/QnHFH/

试试这个..这里排序是在值上完成的。您可以使用.text基于文本进行排序

$("select").html($("select option").sort(function (a, b) {
     return a.text == b.text ? 0 : a.value < b.value ? -1 : 1  ;
}));

演示

文本排序: 演示2

 return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 ;

在文本中对值进行排序: 演示3

$("select").html($("select option").sort(function (a, b) {
    var a1 =  parseFloat(a.text.match(/\(.*?([\d.]+).*?\)/)[1].replace("$",""));
    var b1 =  parseFloat(b.text.match(/\(.*?([\d.]+).*?\)/)[1].replace("$",""));
    return a.text == b.text ? 0 : a1 < b1 ? -1 : 1
}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM