我有:
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
我已连接到update: function(event, ui) { }
,但我不确定如何获取元素的原始位置和新位置。如果我将第3项移到第1项以上,我希望原始位置为 2 (0基于索引),而第3项的新位置为 0 。< / p>
答案 0 :(得分:87)
$('#sortable').sortable({
start: function(e, ui) {
// creates a temporary attribute on the element with the old index
$(this).attr('data-previndex', ui.item.index());
},
update: function(e, ui) {
// gets the new and old index then removes the temporary attribute
var newIndex = ui.item.index();
var oldIndex = $(this).attr('data-previndex');
$(this).removeAttr('data-previndex');
}
});
答案 1 :(得分:17)
调用更新函数时,ui.item.sortable尚未更新,但UI元素已在视觉上移动。
这允许您在更新功能中获取旧位置和新位置。
$('#sortable').sortable({
update: function(e, ui) {
// ui.item.sortable is the model but it is not updated until after update
var oldIndex = ui.item.sortable.index;
// new Index because the ui.item is the node and the visual element has been reordered
var newIndex = ui.item.index();
}
});
答案 2 :(得分:10)
您可以通过多种方式检查旧位置和新位置。我会把它们放到数组中。
$('#sortable').sortable({
start: function(e, ui) {
// puts the old positions into array before sorting
var old_position = $(this).sortable('toArray');
},
update: function(event, ui) {
// grabs the new positions now that we've finished sorting
var new_position = $(this).sortable('toArray');
}
});
然后,您可以轻松提取所需内容。
答案 3 :(得分:5)
我一直在寻找同一问题的答案。根据Frankie的贡献,我能够获得开始和结束的“订单”。我使用var的变量范围存在问题,所以我只是将它们存储为.data()而不是本地变量:
$(this).data("old_position",$(this).sortable("toArray"))
和
$(this).data("new_position",$(this).sortable("toArray"))
现在你可以这样调用它(来自更新/结束函数):
console.log($(this).data("old_position"))
console.log($(this).data("new_position"))
仍然归功于弗兰基:)
答案 4 :(得分:3)
这对我有用
$('#sortable').sortable({
start: function(e, ui) {
// puts the old positions into array before sorting
var old_position = ui.item.index();
},
update: function(event, ui) {
// grabs the new positions now that we've finished sorting
var new_position = ui.item.index();
}
});
答案 5 :(得分:1)
这对我有用,
$('#app').sortable({
handle: '.handle',
start: function(evt, ui){
$(ui.item).data('old-ndex' , ui.item.index());
},
update: function(evt, ui) {
var old_index = $(ui.item).data('old-ndex');
var new_index = ui.item.index();
alert('old_index -'+old_index+' new index -'+new_index);
}
});