我有:
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
我已经连接到 update: function(event, ui) { }
,但不确定如何获取元素的原始位置和新位置。如果我将第三个项目移动到第一个项目上面,我希望原始位置是2(从0开始的索引),并且第三个项目的新位置是0。我有:
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
我已经连接到 update: function(event, ui) { }
,但不确定如何获取元素的原始位置和新位置。如果我将第三个项目移动到第一个项目上面,我希望原始位置是2(从0开始的索引),并且第三个项目的新位置是0。$('#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');
}
});
ui.item.data('previndex')
。 - adamj当调用更新函数时,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();
}
});
ui.item.sortable.index
和ui.item.index()
都返回相同的整数。我开始使用ui.item.sortable.dropindex
来获取新索引。 - Mudassir Ali$('#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');
}
});
然后你可以轻松地提取你所需要的内容。
我正在寻找一个与之相同的问题的答案。根据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"))
功劳仍然归于Frankie :)
$('#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();
}
});
这对我有效,
$('#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);
}
});