Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - Keep checked items at top of list

I'm trying to create a checklist that will sort checked items to the top of the list, and when an item is unchecked, it will move below the checked items. Beyond the checked/unchecked sort, items should stay in their original order, regardless of what order they are checked in.

In other words, a five item list should always look like this:
* two
* three
one
four
five

not this:
*three
*two
one
four
five

I've seen examples of how to move clicked items to a specific position in the list, but nothing that takes into account the state of other items in the list.

Ideally I'd also like to animate the transition. Also, is there a way to remember the checked state across multiple pages?

This is the HTML I'm starting with:

<form>
<ul>
<li><label for="one"><input type="checkbox" id="one" />One</label></li>
<li><label for="two"><input type="checkbox" id="two" />Two</label></li>
<li><label for="three"><input type="checkbox" id="three" />Three</label></li>
<li><label for="four"><input type="checkbox" id="four" />Four</label></li>
<li><label for="five"><input type="checkbox" id="five" />Five</label></li>
</ul>
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Select the original list to save the order. When one of the checkboxes is clicked, iterate over it, appending the checked items first and the unchecked items second:

var list = $("ul"),
    origOrder = list.children();

list.on("click", ":checkbox", function() {
    var i, checked = document.createDocumentFragment(),
        unchecked = document.createDocumentFragment();
    for (i = 0; i < origOrder.length; i++) {
        if (origOrder[i].getElementsByTagName("input")[0].checked) {
            checked.appendChild(origOrder[i]);
        } else {
            unchecked.appendChild(origOrder[i]);
        }
    }
    list.append(checked).append(unchecked);
});

Demo: http://jsfiddle.net/scSYV/2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...