【问题标题】:How to display a page with a sorted drop down list?如何显示带有排序下拉列表的页面?
【发布时间】:2013-06-07 02:44:34
【问题描述】:

我有一个选择列表

<select id="select_zone">
  <option value="north">North</option>
  <option value="east">East</option>
  <option value="south">South</option>
  <option value="west">West</option>
</select>

现在我希望列表中的项目使用 jquery 以排序方式出现。我应该能够手动(以随机顺序)在 html 代码中的列表中添加项目。但它们应该在浏览器页面中按字母顺序排列。

我一直在头疼,做了很多研发。但无法在页面加载时找到对 dropdpwnlist 进行排序的方法。 请帮忙!

【问题讨论】:

标签: javascript jquery html sorting select


【解决方案1】:

这是一个使用以下代码的工作小提琴: http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/

http://jsfiddle.net/Rz6xv/

代码:

function sortDropDownListByText() {
    // Loop for each select element on the page.
    $("select").each(function() {

        // Keep track of the selected option.
        var selectedValue = $(this).val();

        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        // Select one option.
        $(this).val(selectedValue);
    });
}

【讨论】:

    【解决方案2】:

    编写一个方法并调用文档 ready()

    function sortMycombo() {
       $("#select_zone").html($('#select_zone option').sort(function(x, y) {
             return $(x).text() < $(y).text() ? -1 : 1;
       }))
       $("#select_zone").get(0).selectedIndex = 0;
       e.preventDefault();
    });
    

    【讨论】:

    • 对于 '$("#select_zone").html' 它表示未解析的函数或方法名称
    • 我使用 Webstorm 作为 IDE
    • 为了包含 jquery,我使用了 cdn '
    【解决方案3】:

    你可以使用 jQuery 和类似的东西:

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

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多