javascript - 使用 jQuery sortable 从数组中排序列表

标签 javascript jquery jquery-ui jquery-ui-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 Fiddle demo .

引用资料:

关于javascript - 使用 jQuery sortable 从数组中排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23963989/

相关文章:

jquery - 尝试拉取 json img 时未定义

php - Zend Form AJAX 弹出窗口与 jQuery

javascript - jQuery UI 可按 desc 顺序设置

jquery - 合并对话框代码

jquery - 将 CSS3 转换和动画与 jQuery addClass/removeClass 结合使用的最佳方法是什么?

javascript - 防止 SVG 模式的拉伸(stretch)/preserveAspectRatio

javascript - 花式框图像标题和计数不起作用

javascript - 如何使用 javascript 移动 SVG 线

javascript - 使用 AJAX 集成 Asana API

Javascript:更改id中的css子节点