假设我有以下可排序对象:
<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>
排序后,所有项目的 data-id
属性都需要更新为其新位置。
我尝试过这个:
$('.photos').sortable({
stop: function(event, ui){
$(ui.item).attr('data-id', ui.item.index()+1);
}
});
但它只更新已移动项目的 data-id,而不更新其他项目。我怎样才能做到这一点?
最佳答案
使用update
事件,在其中循环每个.photo
并根据其当前索引设置data-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
});
}
});
Here's a fiddle
关于jQuery UI Sortable - 更新项目 data-id 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24958212/