js-sortable
是一個(gè)用于使 HTML 列表可排序的 JavaScript 庫(kù)。它主要依賴于在客戶端進(jìn)行操作,處理列表項(xiàng)之間的拖放和排序。然而,它本身并不直接支持從遠(yuǎn)程服務(wù)器獲取數(shù)據(jù)。
如果您希望實(shí)現(xiàn)可排序列表并顯示來自遠(yuǎn)程服務(wù)器的數(shù)據(jù),您可以采取以下步驟:
fetch
API 或 XMLHttpRequest
)從遠(yuǎn)程服務(wù)器獲取數(shù)據(jù)。js-sortable
對(duì)解析后的數(shù)據(jù)創(chuàng)建可排序列表。以下是一個(gè)簡(jiǎn)單的示例,展示了如何將遠(yuǎn)程數(shù)據(jù)與 js-sortable
結(jié)合使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sortable List with Remote Data</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Sortable/latest/Sortable.min.css">
</head>
<body>
<ul id="sortableList"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/latest/Sortable.min.js"></script>
<script>
// 獲取遠(yuǎn)程數(shù)據(jù)
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 創(chuàng)建可排序列表
const sortableList = new Sortable(document.getElementById('sortableList'), {
animation: 150,
onUpdate: function (event) {
console.log('Sorted list:', event.target.children);
}
});
// 將數(shù)據(jù)添加到列表中
data.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = item.name;
listItem.dataset.id = item.id;
sortableList.append(listItem);
});
})
.catch(error => {
console.error('Error fetching remote data:', error);
});
</script>
</body>
</html>
在這個(gè)示例中,我們首先使用 fetch
API 從遠(yuǎn)程服務(wù)器獲取數(shù)據(jù),然后將其解析為 JSON 格式。接下來,我們使用 js-sortable
創(chuàng)建一個(gè)可排序列表,并將解析后的數(shù)據(jù)添加到列表中。當(dāng)列表項(xiàng)的順序發(fā)生變化時(shí),onUpdate
事件會(huì)被觸發(fā),您可以在其中處理排序后的數(shù)據(jù)。