Getting the position of the element in a list when

2019-01-09 04:11发布

I have a sortable list like this one: http://jqueryui.com/demos/sortable

Is it possible to get the start and end position of the element in the list, when it has been moved? I'm talking about their position number, in the list.

For example, if I move element 2 to position 5 in the list, I'd like to assign those two numbers to variables.

I'm new to jQuery - any help would be much appreciated.

3条回答
【Aperson】
2楼-- · 2019-01-09 04:22

SOLUTION:

$(function() {
    $('ul#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        update: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var end_pos = ui.item.index();
            alert(start_pos + ' - ' + end_pos);
        }
    });
});
  • NOTE: Updated to make use of jQuery data() method under advice of Alconja
查看更多
放我归山
3楼-- · 2019-01-09 04:26

For some reason ui.item.index() did not work for me.

This did:

update: function (event, ui) 
{
    var index = $('li', $(ui.item).parent()).index(ui.item);
    alert(index);
}
查看更多
我命由我不由天
4楼-- · 2019-01-09 04:33

I believe what you are looking to do is done with the serialize method. Serialize is get the new order of the list.

查看更多
登录 后发表回答