[英]Sort list from array with jQuery sortable
我知道如何將列表元素的位置保存到數據庫或本地存儲或類似的東西。 但是,如何使用JavaScript從數組中保存的位置對列表進行重新排序?
我看了一下StackOverflow並發現了以下代碼,但是它不起作用(它只是清空列表):
// Get your list items
var items = $('#sortable').find('li');
// The new index order for each item
var order = store.get('sortableIDsOrder');
// Map the existing items to their new positions
var orderedItems = $.map(order, function(value) {
return items.get(value);
});
// Clear the old list items and insert the newly ordered ones
$('#sortable').empty().html(orderedItems);
我的數組看起來像:
[portrait-sms,portrait-pc,portrait-mail,portrait-calendar,portrait-facebook,portrait-twitter,portrait-whatsapp,portrait-skype,portrait-viber,portrait-instagram]
我的HTML看起來像:
<li id="portrait-sms"><a href="sms:">...</li>
<li id="portrait-mail"><a href="mailto:">...</li>
<li id="portrait-pc"><a href="#">...</li>
...
僅考慮數組(我假設您已從某處檢索到),我能想到的最簡單的解決方案是:
// assuming this is the array you've recovered from whereever:
var storedArray = ['portrait-sms',
'portrait-pc',
'portrait-mail',
'portrait-calendar',
'portrait-facebook',
'portrait-twitter',
'portrait-whatsapp',
'portrait-skype',
'portrait-viber',
'portrait-instagram'];
function reorder(orderedArray) {
// caching variables:
var el, pre, p;2
// iterating over the elements of the array, using Array.prototype.forEach:
orderedArray.forEach(function (a, b, c) {
// a: the current element in the array,
// b: the index of the current element in the array,
// c: the array itself
if (b > 0) {
// caching the element with the id of the element in the array:
el = document.getElementById(a);
// finding the parentNode of that element:
p = el.parentNode;
// getting the previous element:
pre = document.getElementById(c[b - 1]);
// inserting the element with the id of the current element
// before the nextSibling of the element with the id of the
// previous element in the array:
p.insertBefore(el, pre.nextSibling);
}
});
}
reorder(storedArray);
JS小提琴演示 。
參考文獻:
如果您事先知道數據庫數組中包含的元素並且它們具有靜態值,則可以通過遍歷數據庫數組並形成在加載UI時使用的新JS數組來創建新的JavaScript數組變量。
另一方面,如果您的要求是僅在UI加載期間對數組進行排序,而不是以固定的順序顯示元素(從數據庫中檢索出),則可以使用諸如DataTable之類的JQuery Table插件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.