这应该做你想要的。但真的不是微不足道的,而且非常适合处理与您提供的完全一样的标记。如果你不明白这一点,或者它对你发表评论不起作用。
在此处查看快速演示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++;
});