How do I track what position an element is when its position in a sortable list changes?
问题:
回答1:
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({ stop: function(event, ui) { alert("New position: " + ui.item.index()); } });
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
回答2:
I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so:
$( "#sortable" ).sortable({ start: function(event, ui) { ui.item.startPos = ui.item.index(); }, stop: function(event, ui) { console.log("Start position: " + ui.item.startPos); console.log("New position: " + ui.item.index()); } });
回答3:
Use update instead of stop
http://api.jqueryui.com/sortable/
update( event, ui )
Type: sortupdate
This event is triggered when the user stopped sorting and the DOM position has changed.
.
stop( event, ui )
Type: sortstop
This event is triggered when sorting has stopped. event Type: Event
Piece of code: