Сортировать список из массива с помощью сортировки jQuery

Я знаю, как сохранить положение элементов списка в базе данных или локальном хранилище или что-то подобное. Но как я могу переупорядочить список с помощью JavaScript из позиций, которые сохранены в моем массиве?

Я посмотрел Stackru и нашел следующий код, но он не работает (он просто очищает мой список):

// 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>
...

2 ответа

Решение

Самое простое решение, которое я могу придумать, учитывая только массив (который, я полагаю, вы откуда-то получили), это:

// 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.

Рекомендации:

  • Array.prototype.forEach(),
  • Node.insertBefore(),
  • Node.parentNode,

Если вы уже знаете, какие элементы у вас есть в массиве базы данных, и у них есть статические значения, вы можете создать новую переменную массива JavaScript, перебирая массив базы данных и формируя новый массив JS, который вы используете при загрузке пользовательского интерфейса.

С другой стороны, если ваше требование состоит в том, чтобы просто сортировать массив во время загрузки пользовательского интерфейса вместо отображения элементов в фиксированном порядке (полученном из базы данных), вы можете использовать плагины таблиц JQuery, например DataTable.

Другие вопросы по тегам