我知道如何将列表元素的位置保存到数据库或本地存储或类似的东西中。但是,如何使用 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);
引用资料:
关于javascript - 使用 jQuery sortable 从数组中排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23963989/