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

标签 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>

排序后,所有项目的 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/

相关文章:

javascript - 如何使用 jquery 删除字段?

jquery - 想要图像向上滚动,然后卡住,然后文本滚动到它上面

jquery - 将背景图像滑动到图像链接后面

jquery - 需要显式调用 .button() 来应用 JQuery UI 样式吗?

javascript - 如何获取 jQuery UI 小部件的名称?

jquery - 引用错误: Can't find variable: Rails

javascript - 我想将一组 jquery 选择器存储为要延迟评估的数据结构

jquery - 如何为html内容中的不同 block 运行相同的jquery代码?

php - 带有 ajax 更新的 Jqueryui 可排序列表

javascript - 为什么 jQuery Datepicker 在输入数字并按下回车键时选择今天的日期?