【问题标题】:Sort Select box by price with jQuery使用 jQuery 按价格对选择框进行排序
【发布时间】:2022-01-10 09:34:28
【问题描述】:

我希望选项按价格排序。我尝试了不同的代码,但没有成功!

这是我的普通盒子:

 <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 做到这一点?

【问题讨论】:

  • 好的...那么您尝试了什么?你是如何创建选择元素的?
  • 您提供的信息不足以了解您的实际需求。请提供有关如何填充数据的更多信息,以便您可以在排序后从那里创建选项,或者如果它是一个数组,您可以先对数组进行排序,然后将其传递给 select。
  • @Sanjeev_gupta2812 完全清楚。此外,解决方案也不是微不足道的,所以 OP 无法解决它或想出一些努力是可以理解的
  • 与提供的答案只有细微差别,但我建议将价格添加为 value= 属性或 data-price= 并使用整数单位为简单起见,例如 data-price=200 data-price=150 (而不是比 2 和 1.5)那么您不需要复杂(并且可能很脆弱)的正则表达式来提取它。

标签: html jquery jquery-selectbox


【解决方案1】:

不重要

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 2018-12-06
    • 2017-07-19
    • 2018-02-14
    相关资源
    最近更新 更多