我有一个用json生成的列表,它可以使用RubaXa / Sortable插件进行排序。 我需要在排序列表时添加列表中的项目位置。因此,当向上或向下移动项目时,项目位置指示符将发生变化。 我评论了一些问题。
可排序功能:
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;
}
答案 0 :(得分:1)
要在移动时移动项目位置,您可以使用onEnd
事件代替onMove
。onEnd
您可以使用evt.newIndex
访问位置。请查看以下代码段
Sortable.create(sortTrue, {
group: "sorting",
sort: true,
onEnd: function(evt) {
$(evt.item).parent().find('.list-group-item').each(function() {
$(this).find('span').text($(this).index() + 1);
});
}
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="result">Drage the list item to see position</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<!-- Latest Sortable -->
<script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>
<!-- sort: true -->
<div id="sortTrue" class="list-group">
<div class="list-group-item"><span>1</span> foo</div>
<div class="list-group-item"><span>2</span> bar</div>
<div class="list-group-item"><span>3</span> baz</div>
<div class="list-group-item"><span>4</span> qux</div>
<div class="list-group-item"><span>5</span> quux</div>
</div>
</body>
</html>
&#13;