jQuery UI 정렬 가능, 업데이트 이벤트에서 현재 위치와 새 위치를 결정하는 방법은 무엇입니까?
-
05-07-2019 - |
문제
나는 가지고있다:
<ul id="sortableList">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
나는 에 유선으로 연결했습니다 update: function(event, ui) { }
하지만 요소의 원래 위치와 새 위치를 얻는 방법을 잘 모르겠습니다.항목 3을 항목 1 위로 이동하면 원래 위치가 2 (0 기반 인덱스) 및 항목 3의 새 위치는 0.
해결책
$('#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');
}
});
다른 팁
업데이트 기능이 호출되면 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();
}
});
구식과 새 직책을 확인할 수있는 몇 가지 가능성이 있습니다. 나는 그것들을 배열에 넣을 것이다.
$('#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');
}
});
그런 다음 필요한 것을 쉽게 추출 할 수 있습니다.
나는 같은 문제에 대한 답을 찾고있었습니다.Frankie가 기여한 내용을 바탕으로 시작 및 끝 "주문"을 모두 얻을 수 있었습니다.var를 사용하는 변수 범위에 문제가 있어서 로컬 변수 대신 .data()로 저장했습니다.
$(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"))
신용은 여전히 Frankie에게 있습니다 :)
이것은 나를 위해 효과가있었습니다
$('#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();
}
});
이것은 나를 위해 작동합니다.
$('#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);
}
});
제휴하지 않습니다 StackOverflow