gpt4 book ai didi

jQuery UI Sortable - 更新项目 data-id 属性

转载 作者:行者123 更新时间:2023-12-01 06:13:19 25 4
gpt4 key购买 nike

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

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com