按价格 jQuery 对 Select 框进行排序
Sort Select box by price with jQuery
我希望选项按价格排序。我尝试了不同的代码,但我没有成功!
这是我的普通盒子:
<select id="product-list">
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
</select>
但我的意思是这样的:
<select id="product-list">
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
</select>
jQuery如何做到这一点?
不平凡
const re = /\[(\d+\.?\d*)$\]/; // matches an amount
const opts = $("#product-list").find("option"); // get the options
opts.sort(function(a,b) { // sort them using the textContent
const a_amt = a.textContent.match(re)[1];
const b_amt = b.textContent.match(re)[1];
return a_amt-b_amt;
})
$("#product-list").html(opts); // re-insert the sorted options
$("#product-list")[0].selectedIndex = 0; // select the new first option
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="product-list">
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
</select>
我希望选项按价格排序。我尝试了不同的代码,但我没有成功!
这是我的普通盒子:
<select id="product-list">
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
</select>
但我的意思是这样的:
<select id="product-list">
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
</select>
jQuery如何做到这一点?
不平凡
const re = /\[(\d+\.?\d*)$\]/; // matches an amount
const opts = $("#product-list").find("option"); // get the options
opts.sort(function(a,b) { // sort them using the textContent
const a_amt = a.textContent.match(re)[1];
const b_amt = b.textContent.match(re)[1];
return a_amt-b_amt;
})
$("#product-list").html(opts); // re-insert the sorted options
$("#product-list")[0].selectedIndex = 0; // select the new first option
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="product-list">
<option>product 1- [2$]</option>
<option>product 2- [4$]</option>
<option>product 3- [0.5$]</option>
<option>product 4- [1.5$]</option>
</select>