gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:52 25 4
gpt4 key购买 nike

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

这是示例 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/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);

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

关于javascript - 使用javascript重新排序选择框中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15555741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com