拖动/删除元素在列表中的位置(ui.sortable)
我有一个像这样的可排序列表: http : //jqueryui.com/demos/sortable
是否有可能在列表移动时获取元素的开始和结束位置? 我在谈论他们的位置编号,在列表中。
例如,如果我将元素2移动到列表中的位置5,我想将这两个数字分配给变量。
我是jQuery的新手 – 任何帮助都会非常感激。
- 演示: http : //so.lucafilosofi.com/getting-the-position-of-the-element-in-a-list-when-its-drag-dropped-ui-sortable/
解:
$(function() { $('ul#sortable').sortable({ start: function(event, ui) { var start_pos = ui.item.index(); ui.item.data('start_pos', start_pos); }, update: function(event, ui) { var start_pos = ui.item.data('start_pos'); var end_pos = ui.item.index(); alert(start_pos + ' - ' + end_pos); } }); });
- 注意:已更新,以便在Alconja的建议下使用jQuery data()方法
我相信你要做的是用serialize方法完成的。 Serialize是获取列表的新顺序。
出于某种原因, ui.item.index()
对我不起作用。
这样做:
update: function (event, ui) { var index = $('li', $(ui.item).parent()).index(ui.item); alert(index); }