这是我当前的代码,一切正常。问题是我需要找出被替换的ID,而不是索引。因此,例如,如果将Item 3移动到Item 5,我需要Start变量为127,End变量为129。如何更改我的代码以获取此信息?
$(function() {
$( "#sortable" ).sortable({
start: function(event, ui) {
ui.item.startPos = ui.item.index();
},
stop: function(event, ui) {
alert("Start position: " + ui.item.startPos);
alert("New position: " + ui.item.index());
alert("Item Moved: " + $(ui.item).attr('id'));
var start = ui.item.startPos;
var end = ui.item.index();
var id = $(ui.item).attr('id');
$.ajax({
data: (start, end, id),
type: 'POST',
url: 'update_order.php?start='+start+'&end='+end+'&id='+id+''
});
}
});
$( "#sortable" ).disableSelection();
});
<ul id="sortable">
<li class="ui" id="125"><span></span>Item 1</li>
<li class="ui" id="126"><span></span>Item 2</li>
<li class="ui" id="127"><span></span>Item 3</li>
<li class="ui" id="128"><span></span>Item 4</li>
<li class="ui" id="129"><span></span>Item 5</li>
<li class="ui" id="130"><span></span>Item 6</li>
<li class="ui" id="131"><span></span>Item 7</li>
</ul>
答案 0 :(得分:1)
stop
事件中提供了所需的所有信息。
ui.item
是您移动的项目。ui.item.prev()
/ ui.item.next()
是已被&#34;替换的项目&#34;
$(function () {
$("#sortable").sortable({
stop: function (event, ui) {
var moved = ui.item,
replaced = ui.item.prev();
// if replaced.length === 0 then the item has been pushed to the top of the list
// in this case we need the .next() sibling
if (replaced.length === 0) {
replaced = ui.item.next();
}
console.log(moved.attr("id"), replaced.attr("id"));
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<ul id="sortable">
<li class="ui" id="125"><span></span>Item 1</li>
<li class="ui" id="126"><span></span>Item 2</li>
<li class="ui" id="127"><span></span>Item 3</li>
<li class="ui" id="128"><span></span>Item 4</li>
<li class="ui" id="129"><span></span>Item 5</li>
<li class="ui" id="130"><span></span>Item 6</li>
<li class="ui" id="131"><span></span>Item 7</li>
</ul>
&#13;