javascript - 如何显示带有排序下拉列表的页面?

标签 javascript jquery html sorting select

我有一个选择列表

<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 进行排序的方法。 请帮忙!

最佳答案

这是一个使用以下代码的工作 fiddle : 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);
    });
}

关于javascript - 如何显示带有排序下拉列表的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040915/

相关文章:

javascript - 将 'onclick' 与输入元素一起使用时重定向

javascript - div 可以容纳多少个 10 x 10 的盒子?

javascript - Angularjs input[placeholder] 指令与 ng-model 中断

javascript - 更新后父 View 未在 Electron 中的 <webview> 上设置全局变量

javascript - jQuery .data() 从存储的数组中删除项目

javascript - 哪个控件触发了该事件

javascript - 如何使用 Plunker 测试选项卡集中的 angular-ui-tinymce

javascript - jQuery 可放置元素 id 未定义

javascript - 为什么 DOM 对象在控制台中的显示与一般 Javascript 对象不同?

html - CSS – 标题显示 : table element – positioning issue