我:jQuery UI可排序,如何確定更新事件中的當前位置和新位置?
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
我已經連入了update: function(event, ui) { }
但我不知道如何獲取元素的原始和新的位置。如果我將項目3移動到項目1上方,我希望原始位置爲(0基於索引),並且項目3的新位置爲。
我:jQuery UI可排序,如何確定更新事件中的當前位置和新位置?
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
我已經連入了update: function(event, ui) { }
但我不知道如何獲取元素的原始和新的位置。如果我將項目3移動到項目1上方,我希望原始位置爲(0基於索引),並且項目3的新位置爲。
$('#sortable').sortable({
start: function(e, ui) {
// creates a temporary attribute on the element with the old index
$(this).attr('data-previndex', ui.item.index());
},
update: function(e, ui) {
// gets the new and old index then removes the temporary attribute
var newIndex = ui.item.index();
var oldIndex = $(this).attr('data-previndex');
$(this).removeAttr('data-previndex');
}
});
您有幾種可能性來檢查舊的和新的位置。我會把它們放入數組中。
$('#sortable').sortable({
start: function(e, ui) {
// puts the old positions into array before sorting
var old_position = $(this).sortable('toArray');
},
update: function(event, ui) {
// grabs the new positions now that we've finished sorting
var new_position = $(this).sortable('toArray');
}
});
然後你可以很容易地提取你所需要的。
列表項必須有ID。否則它會生成空數組 – Atara 2017-11-23 13:08:05
我正在尋找同一問題的答案。基於Frankie的貢獻,我能夠獲得開始和結束「訂單」。我使用var曾與變量的作用域的問題,所以我只是將它們存儲爲。數據(),而不是本地變量:
$(this).data("old_position",$(this).sortable("toArray"))
和
$(this).data("new_position",$(this).sortable("toArray"))
現在你可以把它像這樣(從更新/結束功能):
console.log($(this).data("old_position"))
console.log($(this).data("new_position"))
信貸還是到弗蘭基:)
當調用更新函數時,ui.item.sortable尚未更新,但UI元素已在視覺上移動。
這使您可以在更新功能中獲得舊的位置和新的位置。
$('#sortable').sortable({
update: function(e, ui) {
// ui.item.sortable is the model but it is not updated until after update
var oldIndex = ui.item.sortable.index;
// new Index because the ui.item is the node and the visual element has been reordered
var newIndex = ui.item.index();
}
});
這是最好的答案和最乾淨的解決方案!感謝Richard! – Whizkid747 2013-11-01 11:50:43
不適用於jQuery 1.7,jQuery UI 1.8 - 雖然這個解決方案看起來非常有希望 – user1702401 2013-11-12 13:36:05
具體而言:ui.item.sortable.index不存在;和ui.item.sortable()。index()返回所有已更新的索引。 – user1702401 2013-11-12 13:41:50
這爲我工作
$('#sortable').sortable({
start: function(e, ui) {
// puts the old positions into array before sorting
var old_position = ui.item.index();
},
update: function(event, ui) {
// grabs the new positions now that we've finished sorting
var new_position = ui.item.index();
}
});
這對我有用!值得注意的是,如果您需要在update()中引用old_position,則只需在可排序之前聲明它即可。 – nick 2015-04-24 09:47:39
這對我的作品,
$('#app').sortable({
handle: '.handle',
start: function(evt, ui){
$(ui.item).data('old-ndex' , ui.item.index());
},
update: function(evt, ui) {
var old_index = $(ui.item).data('old-ndex');
var new_index = ui.item.index();
alert('old_index -'+old_index+' new index -'+new_index);
}
});
從理查德最後的答案與upvotes的數量最少是最好的和乾淨的解決方案,尤其是當你使用AngularJS或任何其他MVC框架,你不想在控制器中讀取自定義屬性! – Whizkid747 2013-11-01 11:52:01