我有一個使用json生成的列表,它可以使用RubaXa/Sortable插件進行排序。 我需要在排序列表時添加列表中的項目位置。所以當向上或向下移動一個項目時,項目位置指示器將會改變。 我評論了一些問題。在使用Sortable排序期間/之後顯示使用json創建的列表中的項目位置
可排序功能:
var listPos;
Sortable.create(list-group, {
handle: '.driver',
animation: 150,
onMove: function (evt) {
evt.dragged;
evt.draggedRect;
evt.related;
evt.relatedRect;
listPos = $(this).closest('.list-group').children('.list-group-item').index(this); // error finding the position in the list
console.log(evt); // event is shown in the console
console.log(listPos); // this is showing always -1 after the event
}
});
的JSON:
[
{
"name": "item 1",
"acr": "it1"
},
{
"name": "item 2",
"acr": "it2"
},
{
"name": "item 3",
"acr": "it3"
},
{
"name": "item 4",
"acr": "it4"
}
]
的HTML:
<div class="col-md-4">
<div id="printList" class="list-group">
</div>
</div>
解析/打印JSON:
var xmlhttp = new XMLHttpRequest();
var url = "/list.json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
showListPos = listPos; // showListPost in undefined
var arr = JSON.parse(response);
var i;
var out = "";
var drawPos = "<div class='position'>" + showListPos + "</div>"; //
for (i = 0; i < arr.length; i++) {
out += "<div class='list-group-item'>" +
"<p>" + drawPos + "</p>"
"<h3><span>" + arr[i].name + "</span>" +
arr[i].acr +
"</h3></div>";
}
out += "";
document.getElementById("printList").innerHTML = out;
}
你嘗試'$ (this).closest('。list-group')。index()' –
感謝您的快速回復,是的,我做了相同的結果。輸出是-1 –