已连接的可排序列表

时间:2009-12-02 18:39:23

标签: javascript jquery jquery-ui jquery-ui-sortable

我正在使用连接的可排序列表,并且需要添加额外列表的功能,但它不起作用。

我有一个像这样的XHTML:

<div id="content">
   <div class="line">
        <span class="element">1</span>
        <span class="element">2</span>
        <span class="element">3</span>
   </div>
   <div class="line">
        <span class="element">4</span>
        <span class="element">5</span>
        <span class="element">6</span>
   </div>
</div>

其中元素必须是可排序的,并且用户必须能够将它们从一个.line更改为另一个.line。 但是在排序时,必须添加一个空的额外行,以防用户想要将元素放在新行中。

我尝试在div#content中添加div.line,但不能删除元素。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

这应该做你想要的。但实际上非常简单,并且非常适合处理与您提供的标记完全相同的标记。如果您不理解这一点,或者它不适用于您发表评论。

点击此处查看快速演示http://jsbin.com/uhoga(代码为http://jsbin.com/uhoga/edit

//pseudo unique id generator
var uid = 0;

function starter() {
    var lines = $("div.line");
    var len = lines.size();
    //insert empty div.line at end with "unique" id
    lines.eq(len-1).after("<div class='line' id='line"+uid+"' />");
    //make it a sortable too
    $('#line'+uid).sortable({
        //connect with other div.lines which don't have same id
        connectWith: 'div.line:not([id=line'+uid+'])',
        start: starter,
        stop: stopper,
        //needed to stop some "flickering"
        appendTo: 'div.line[id=line'+uid+']',
        items: 'span.element'
    });
    uid++;
    //refresh this sortable so it sees the newly inserted as possible "target"
    $(this).sortable('refresh');
}

function stopper() {
    //remove all div.lines which are empty (have no span.element children)
    $("div.line:not(:has(> span.element))").remove();
}

//initial setup
$("div.line").each(function(i, ele) {
    var jEle = $(ele);
    //assuming the initially present div.line elements have no id
    jEle.attr("id", "line"+uid);
    jEle.sortable({
        connectWith: 'div.line:not([id=line'+uid+'])',
        start: starter,
        stop: stopper,
        //needed to stop some "flickering"
        appendTo: 'div.line[id=line'+uid+']',
        items: 'span.element'
    });
    uid++;
});