1

I have a large list of checkboxes (600+), would it be possible to use js to sort them alphabetically and then rearrange them by manipulating the dom?

from

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

to

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

1 回答 1

5

如果您可以将它们包装在标签中,无论如何这是一个很好的做法,您可以这样做:

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);

 });

演示

于 2013-07-02T18:56:25.623 回答