jQuery UI Sortable - 更新项数据id属性

GST*_*TAR 1 jquery jquery-ui jquery-ui-sortable

假设我有以下可排序对象:

<ul class="photos ui-sortable">
    <li class="photo" data-id="1"></li>
    <li class="photo" data-id="2"></li>
    <li class="photo" data-id="3"></li>
    <li class="photo" data-id="4"></li>
    <li class="photo" data-id="5"></li>
    <li class="photo" data-id="6"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

排序后,data-id需要使用新位置更新所有项目的属性.

我试过这个:

$('.photos').sortable({
    stop: function(event, ui){
        $(ui.item).attr('data-id', ui.item.index()+1);
    }
});
Run Code Online (Sandbox Code Playgroud)

但它只更新已移动项目的数据ID,而不更新其他项目的数据ID.我怎样才能做到这一点?

bil*_*can 8

使用update事件,在那里只是循环遍历每个.photodata-id根据其当前索引设置:

$('.photos').sortable({
    update: function(event, ui) {
        $('.photo').each(function(i) { 
           $(this).data('id', i + 1); // updates the data object
           $(this).attr('data-id', i + 1); // updates the attribute
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴