按字母顺序对输入/复选框元素进行排序

sort input/checkbox elements alphabetically

本文关键字:元素 复选框 排序 输入 顺序      更新时间:2023-09-26

我有一个很大的复选框列表(600+),是否可以使用js按字母顺序排序,然后通过操纵dom来重新排列它们?

来自

 <form id="stuff">
      <input type="checkbox" value="bbb" /> bbb
      <input type="checkbox" value="aaa" /> aaa
      <input type="checkbox" value="ccc" /> ccc
 </form>

 <form id="stuff">
      <input type="checkbox" value="aaa" /> aaa
      <input type="checkbox" value="bbb" /> bbb
      <input type="checkbox" value="ccc" /> ccc
 </form>

如果您可以将它们包装在标签中,这是一种很好的做法,那么您可以这样做:

Html

<form id="stuff">
    <label>
        <input type="checkbox" value="bbb" />bbb</label>
    <label>
        <input type="checkbox" value="aaa" />aaa</label>
    <label>
        <input type="checkbox" value="ccc" />ccc</label>
</form>

脚本

var sortByText = function (a, b) {
     return $.trim($(a).text()) > $.trim($(b).text());
 }
 $(document).ready(function () {
     var sorted = $('#stuff label').sort(sortByText);
     $('#stuff').append(sorted);
 });

演示