[英]Detect if element position was changed in Jquery UI sortable
我使用以下代碼對網站上的商品進行重新排序:
$(document).ready(function () {
$("#my-list").sortable({
stop: function (event, ui) {
var id = $(ui.item).attr('id');
var url = '/en/account/changeposition?id=idreplace&position=posReplace';
url = url.replace("idreplace", id);
url = url.replace("posReplace", ui.item.index());
window.location.href = url;
},
distance: 15
});
});
但是,即使我不更改元素位置並將元素放置在同一位置,Jquery UI也會調用“停止”功能。
是否可以在不使用自定義數據屬性的情況下檢測元素索引(位置)是否已更改?
// I would like to avoid adding custom data attributes like this:
<li id="id100" data-original-position="1"></li>
<li id="id101" data-original-position="2"></li>
看看這個答案 。
它為我工作如下:
$(selector).sortable({
start: function(event, ui) {
ui.item.data('start_pos', ui.item.index());
},
stop: function(event, ui) {
var start_pos = ui.item.data('start_pos');
if (start_pos != ui.item.index()) {
// the item got moved
} else {
// the item was returned to the same position
}
},
update: function(event, ui) {
$.post('/reorder', $(selector).sortable('serialize'))
.done(function() {
alert('Updated')
});
}
});
除非我缺少任何東西,否則update
事件將是您的最佳選擇。 根據文檔
當用戶停止排序並且DOM位置已更改時,將觸發此事件。
因此,如果您僅在用戶停止拖動時擔心的是索引是否更改,則只需使用update
,省去了設置和評估數據屬性的麻煩。
從http://api.jqueryui.com/sortable/#event-update獲得了
update(event,ui)類型:sortupdate用戶停止排序並且DOM位置已更改時觸發此事件
據此,更新是您唯一需要的內容...因為更新會檢測DOM位置是否已更改。
盡管對於大多數情況而言,使用update事件似乎是最好的答案,但是要記住,如果元素沒有移動,則不會觸發此事件。
盡管在大多數情況下這可能很好,但是在可排序停止時您可能需要運行一些代碼,但未進行任何更改(我發現自己需要重置一些全局變量)。 只有使用接受的答案才有可能。
創建一個布爾
sortableChanged = false;
在JQuery
sortable的更新中設置為true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.