jquery - 在排序更改事件期间更新排序顺序 - jQuery UI

标签 jquery jquery-ui jquery-ui-sortable

我希望列表元素的值是排序事件期间排序位置的索引。

此值应在排序更改事件期间自动更新。

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

相关文章:

javascript - 通过ajax发送表单,html节点选择数据发送

javascript - jQuery:如果距顶部超过 150px 则执行

jquery - ASP.NET MVC 5 不呈现 jQuery UI CSS 包

javascript - jQuery 中的自定义数据可排序?

jquery - 使用 'clone' 助手执行可拖动事件后,如何删除原始元素?

javascript - $对象不支持属性或方法 'live'

javascript - jQuery.cookie 不存储我的 JSON 字符串

jquery.validate.js JavaScript 错误

javascript - jquery ui 可调整 float 元素的大小。

javascript - jQuery UI 可排序连接列表 css 问题