将选中的项目保留在列表顶部 [英] Keep checked items at top of list

查看:67
本文介绍了将选中的项目保留在列表顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个清单,将检查的项目排序到列表顶部,当取消选中某个项目时,它将移动到选中的项目下方。除了选中/未选中的排序,项目应保持原始顺序,无论签入的顺序如何。

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?

这是我开始使用的HTML:

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>


推荐答案

选择原始列表以保存订单。单击其中一个复选框时,对其进行迭代,首先附加选中的项目,然后附加未选中的项目:

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

演示: http://jsfiddle.net/scSYV/2

这篇关于将选中的项目保留在列表顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆