我有一个很大的复选框列表(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>
Run Code Online (Sandbox Code Playgroud)
至
<form id="stuff">
<input type="checkbox" value="aaa" /> aaa
<input type="checkbox" value="bbb" /> bbb
<input type="checkbox" value="ccc" /> ccc
</form>
Run Code Online (Sandbox Code Playgroud)
如果你可以将它们包装在标签中,这是一个很好的做法,你可以这样做:
<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>
Run Code Online (Sandbox Code Playgroud)
var sortByText = function (a, b) {
return $.trim($(a).text()) > $.trim($(b).text());
}
$(document).ready(function () {
var sorted = $('#stuff label').sort(sortByText);
$('#stuff').append(sorted);
});
Run Code Online (Sandbox Code Playgroud)