jquery – 在没有第一个项目的下拉列表中排序项目

前端之家收集整理的这篇文章主要介绍了jquery – 在没有第一个项目的下拉列表中排序项目前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码在下拉列表中对项目进行排序:
  1. function sortDropDownListByText(selectId) {
  2. $(selectId).html($(selectId + " option").sort(function(a,b) {
  3. return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
  4. }))
  5. }

这样做很好,除非在我的第一个项目中我有一个**“请从列表中选择和项目”消息. . **

有没有办法我可以排序选择列表中的项目,并保持“请选择条目”作为列表中的第一个项目?

编辑:

响应一些答案,“请选择项始终有值0”

解决方法

  1. function sortDropDownListByText(selectId) {
  2. var foption = $('#'+ selectId + ' option:first');
  3. var soptions = $('#'+ selectId + ' option:not(:first)').sort(function(a,b) {
  4. return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
  5. });
  6. $('#' + selectId).html(soptions).prepend(foption);
  7.  
  8. };

是你的功能

猜你在找的jQuery相关文章