我希望列表元素的值是排序事件期间排序位置的索引。
此值应在排序更改事件期间自动更新。
<script type="text/javascript">
$(function() {
$('#sortable').sortable({
start : function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change : function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').html(index-2);
} else {
$('#sortable li:eq(' + (index + 1) + ')').html(index + 1);
}
},
update : function(event, ui) {
var index = ui.item.index();
$('#sortable li:nth-child(' + (index + 1) + ')').html(index);
},
axis : 'y'
});
});
</script>
我创建了一个 fiddle http://jsfiddle.net/jagan2explore/4mcpq/
解释我的要求。
如果我将第一个元素移动到第五个位置,所有其他元素值都会正确更新, 如果我将第 5 个移动到第 1 个,则值会相应更新。
假设如果我将列表元素从 1 移动到 5 以及从 5 移动到 2 而没有离开(在单个排序事件期间),则值不会相应更新。
我错过了什么吗?
任何帮助将不胜感激。提前致谢
最佳答案
试试这个:
update : function(event, ui) {
var index = ui.item.index();
var start_pos = ui.item.data('start_pos');
//update the html of the moved item to the current index
$('#sortable li:nth-child(' + (index + 1) + ')').html(index);
if (start_pos < index) {
//update the items before the re-ordered item
for(var i=index; i > 0; i--){
$('#sortable li:nth-child(' + i + ')').html(i - 1);
}
}else {
//update the items after the re-ordered item
for(var i=index+2;i <= $("#sortable li").length; i++){
$('#sortable li:nth-child(' + i + ')').html(i-1);
}
}
},
演示:jsfiddle
关于jquery - 在排序更改事件期间更新排序顺序 - jQuery UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16082519/