Keep track of the positions of all elements in a jQuery sortable
I'm trying to figure out how I can track how the elements in a jQuery sortable. Let's say that I have four elements (divs) in my sortable, each have an unique id. Let's call them #100, #200, #300 and #400 and they're presented in that order to start with. But when I move #100 to let's say spot number 3, I need to be able to save the new position for this id, but also make sure that the other ones get updated position values aswell.
Am I making any sense? Basically I want to get the positions of each unique id, so I can save the order of the list for later use.
I haven't been able to find something that reports开发者_高级运维 for all the elements in a sortable, just for the one that was moved..
Point me in the right direction? Thanks
You can use the stop-event provided to you in sortable to keep track of the items. This is a small example;
(function($) {
$('#sortable').sortable({
stop: function(e, ui) {
console.log($.map($(this).find('li'), function(el) {
return el.id + ' = ' + $(el).index();
}));
}
});
})(jQuery);
This logs an array of all the items in the sortable with their id's and their current indexes.
Here is a working example on jsfiddle as well: http://jsfiddle.net/beyondsanity/HgDZ9/
According to the docs http://api.jqueryui.com/sortable/#method-toArray I suggest you to use built-in method toArray
.
Example:
$(document).ready(function() {
$('#sortable').sortable({
stop: function(e, ui) {
console.log($('#sortable').sortable('toArray'));
}
});
$('#sortable').disableSelection();
});
Possible duplicate of jQuery UI Sortable Position.
Basically, to get the position of an element within a sortable (or just a plain old parent elemen), just something like
$('#300').index();
This code will return 2 if nothing has been moved (index()
starts counting at zero), and updates when the elements are re-arranged.
Here's a demo: http://jsfiddle.net/XB5Dh/. You can click an element to see its position, and the new position is shown when you drag an element.
精彩评论