【问题标题】:Sort drop down options排序下拉选项
【发布时间】:2014-04-04 07:43:15
【问题描述】:

我正在尝试this solution 整理下拉菜单,但选项中有两位数,14 和 11 在 8 和 9 之前。

我应该如何处理这个问题?

我的代码如下:

<select id="test">
    <option>Size 9</option>
    <option>Size 14</option>
    <option>Size 8</option>
    <option>Size 11</option>
</select>

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

即使只有字符而不是混合字符,我也需要一个解决方案来对下拉列表进行排序。

jsfiddle

【问题讨论】:

  • 你能澄清一下“只有字符”是什么意思吗?你的意思是“小”、“中”和“大”吗?
  • 您正在比较字符串。 Size 14 总是在Size 9 之前排在第一位。为选项输入数值,以便您可以按数字排序。
  • 你想要排序字符串或数字
  • 你到底想要什么?
  • 实际上你是按文本排序的。所以在排序时,它首先对第一个数字进行排序,在这种情况下,1 排在 8,9 之前,然后再排序。

标签: javascript jquery sorting


【解决方案1】:

您可以使用以下 sn-p 顺便说一句将为每个选项设置值:

DEMO jsFiddle

$("#test").html($("#test option").val(function(){
    return this.text.match(/\d+/);
}).sort(function (a, b) {
    var a = parseInt(a.value,10), b = parseInt(b.value,10);
    return a < b ? -1 : 1;
}));

或者不设置值:

DEMO

$("#test").html($("#test option").sort(function (a, b) {
    var a = parseInt(a.text.match(/\d+/),10), b = parseInt(b.text.match(/\d+/),10);
    return a < b ? -1 : 1;
}));

编辑:(以下评论)

您可以像这样跳过排序默认选项:

DEMO

$("#test").html($("#test option").val(function (i) {
    return i !== 0 ? this.text.match(/\d+/) : this.value;
}).sort(function (a, b) {
    var a = parseInt(a.value !== ""?a.value:-1, 10),
        b = parseInt(b.value, 10);
    return a < b ? -1 : 1;
}));

【讨论】:

  • 谢谢;我如何让它忽略第一个选项''?因为那也得到了排序。
【解决方案2】:

你可以按值排序

html

<select id="test">
    <option value='9'>Size 9</option>
    <option value='14'>Size 14</option>
    <option value='8'>Size 8</option>
    <option value='11'>Size 11</option>
</select>

js

$("#test").html($("#test option").sort(function (a, b) {
    return parseInt($(a).val()) == parseInt($(b).val()) ? 0 : parseInt($(a).val()) < parseInt($(b).val()) ? -1 : 1;
}));

DEMO

【讨论】:

    【解决方案3】:

    当您比较两个文本字段时,其中包含一些数字。 比较仅适用于第一个数值。

    例如:如果我们比较 9 号和 14 号,那么你会得到令人惊讶的结果,比如 9 号大于 14 号。这是因为只有第一个数值被比较,所以 14 的值是数字值为 1。

    在您的情况下,一个简单的解决方案可能是将值字段应用于选项并使用值进行比较。

    <select id="test">
        <option value ="9">Size 9</option>
        <option value ="14">Size 14</option>
        <option value ="8">Size 8</option>
        <option value ="11">Size 11</option>
    </select>
    
    $("#test").html($("#test option").sort(function (a, b) {
        return parseInt(a.value,10) == parseInt(b.value,10) ? 0 : parseInt(a.value,10) < parseInt(b.value,10) ? -1 : 1;
    }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多