如何使用js中的符号对列表进行排序

我有一个下拉列表,其中包含一个如下所示的选项列表:

 Please Select 200 <200 >200 Unknown  

我正在尝试按自定义顺序对它们进行排序,所以它看起来像这样:

  Please Select  <200   200   >200  Unknown  

基本上安排它,以便小于选项首先,然后标准,然后大于,然后未知。

这是动态生成的,值可以是任何值,但始终为4,并始终采用该格式。 始终包含未知的,>,<和标准值。

我目前的代码是:

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

哪个显然不起作用,任何想法如何解决这个问题,似乎无法找到任何关于包含> <符号的排序。

提取文本(排除第一个文本),使用排序数组对文本进行排序和交换

使用HTML

  

你可以使用这个脚本( 上面的HTML之后)

 var sortOrder = { '<': 1, // placeholder for the value '>': 3, 'U': 4 } function sortDropDown(target) { // get text var opts = []; $(target + " option").each(function (i) { if (i) opts.push($(this).text()) }); opts.sort(function (a, b) { // get the sort order using the first character var oa = sortOrder[a[0]] || 2; var ob = sortOrder[b[0]] || 2; if (oa > ob) return 1; else if (oa < ob) return -1; else return 0; }); // change the option text $(target + " option").each(function (i) { if (i) $(this).text(opts[i - 1]) }); } sortDropDown("#weightClass") 
 var sortOrder = { '<': 1, '>': 3, 'U': 4 } function sortDropDown(target) { var opts = []; $(target + " option").each(function (i) { if (i) opts.push($(this).text()) }); console.log(opts) opts.sort(function (a, b) { var oa = sortOrder[a[0]] || 2; var ob = sortOrder[b[0]] || 2; if (oa > ob) return 1; else if (oa < ob) return -1; else return 0; }); $(target + " option").each(function (i) { if (i) $(this).text(opts[i - 1]) }); } sortDropDown("#weightClass") 
   

您应该使用排序function来执行所需的特殊排序。
这是排序函数,以及如何使用它的示例:

 var t = ['some other option', '100', '120', '300', '>300', '<300', '<100', '>400', '200', '<200', '>200', 'another special option'] function specialSort(a, b) { var newA, newB; if (a[0] == '<' || a[0] == '>') { newA = parseInt(a.substr(1)) } else if (!isNaN(a)) { newA = parseInt(a) } else { newA = null; } if (b[0] == '<' || b[0] == '>') { newB = parseInt(b.substr(1)) } else if (!isNaN(b)) { newB = parseInt(b) } else { newB = null; } if (newA == null) { return 1; } if (newB == null) { return -1; } if (typeof(newA) == 'number' && typeof(newB) == 'number') { if (newA < newB) { return -1; } else if (newA > newB) { return 1; } else if (newA == newB) { if (a[0] == '<') { return -1; } else if (b[0] == '<') { return 1; } else if (a[0] == '>') { return 1 } else if (b[0] == '>' ) { return -1; } } } return 0; } console.log(t.sort(specialSort)); // Output is ["<100", "100", "120", "<200", "200", ">200", "<300", "300", ">300", ">400", "another special option", "some other option"] 

您可以使用jQuery获取SELECT标记的值并使用以下方法对它们进行排序:

 valuesToSort = [] $('#weightClass').find('option').each(function(){r.push($(this).text())}) valuesToSort.sort(specialSort) 

现在,数组valuesToSort按您希望的方式排序,您可以将值放回到#weightClass标记中。