jQuery sortable get .index() 排序前后?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10467820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery sortable get .index() before and after sorting?
提问by Hailwood
I am using jQuery's sortable on a tagging plugin,
The plugin maintains an array of objects that relate to the li
's in the same order as the actual items.
我在标记插件上使用 jQuery 的 sortable,该插件维护了一个与li
's相关的对象数组,其顺序与实际项目相同。
I need to update the order of the items in the array when the sorting finishes.
排序完成后,我需要更新数组中项目的顺序。
I thought I would just be able to in the start event call $(ui).index()
and in the update event call the same which would give me the initial position, and the final position, but both calls return -1
.
我以为我只能在 start 事件调用$(ui).index()
和 update 事件调用中使用相同的方法,这会给我初始位置和最终位置,但两个调用都返回-1
.
How should I do this?
我该怎么做?
Structure:结构:
<ul>
<li>here<a class="close">x</a></li>
<li>are<a class="close">x</a></li>
<li>some<a class="close">x</a></li>
<li>tags<a class="close">x</a></li>
</ul>
Array Structure:
数组结构:
[{
label: 'here',
value: 36,
element: '$(the li that this info is about)',
index: 0
},
{
label: 'are',
value: 42,
element: '$(the li that this info is about)',
index: 1
},
{
label: 'some',
value: 21,
element: '$(the li that this info is about)',
index: 2
},
{
label: 'tags',
value: 26,
element: '$(the li that this info is about)',
index: 3
}]
JavaScript:
JavaScript:
$('ul').sortable({
start: function(event, ui){...},
update: function(event, ui){...}
});
采纳答案by Brandt Solovij
if .index()
is returning -1, that would suggest you are making that request prior to the element being available to the DOM. oryou have mislabeled a selector and again it does not exist @ time of call or is empty in relation to the .index() function
如果 .index()
返回 -1,则表明您在元素可用于 DOM 之前发出该请求。或者您错误地标记了一个选择器,并且它再次在调用时不存在或与 .index() 函数相关为空
回答by sidarcy
$(function() { $( "#sortable" ).sortable({ update: function(event, ui) { console.log('update: '+ui.item.index()) }, start: function(event, ui) { console.log('start: ' + ui.item.index()) } }); $( "#sortable" ).disableSelection(); });
回答by tim peterson
you can associate some data with each list item to keep track of them like this:
您可以将一些数据与每个列表项相关联以跟踪它们,如下所示:
<ul id="sortable">
<li data-id="1" class="ui-state-default">1</li>
<li data-id="2" class="ui-state-default">2</li>
<li data-id="3" class="ui-state-default">3</li>
</ul>
you can then access this data via jQuery like this:
然后你可以像这样通过 jQuery 访问这些数据:
$('ul li:nth-child(0)').data('id');
$('ul li:nth-child(1)').data('id');
$('ul li:nth-child(2)').data('id');