jQuery UI Sortable Position

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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:

http://jsfiddle.net/7a1836ce/

 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!