0

Подскажите в чем ошибка, в консоле ошибки нету, но сам фильтр работает не правильно, кнопка рейтинга вообще не работае...

document.querySelector('#sort-asc').onclick = function() {
    ascSort('data-price');
}
document.querySelector('#sort-desc').onclick = function() {
    descSort('data-price');
}
document.querySelector('#rating').onclick = function() {
    descSort('data-rating');
}


function ascSort(sortType) {
    let content = document.querySelector('#content');
    for (let i = 0; i < content.children.length - 1; i++) {
        for (let j = 1; j < content.children.length; j++) {
            if (+content.children[i].getAttribute(sortType) > +content.children[j].getAttribute(sortType)) {
                let replacedNode = content.replaceChild(content.children[j], content.children[i]);
                insertAfter(replacedNode, content.children[i]);
            }
        }
    }
}


function descSort(sortType) {
    let content = document.querySelector('#content');
    for (let i = 0; i < content.children.length - 1; i++) {
        for (let j = 1; j < content.children.length; j++) {
            if (+content.children[i].getAttribute(sortType) < +content.children[j].getAttribute(sortType)) {
                let replacedNode = content.replaceChild(content.children[j], content.children[i]);
                insertAfter(replacedNode, content.children[i]);
            }
        }
    }
}

function insertAfter(elem, refElem) {
    return refElem.parentNode.insertBefore(elem, refElem.nextSibling);
}

3
  • Я что не вижу фильтра. Только сортировку пузырьком 8 авг 2020 в 22:23
  • Сюда бы HTML из трех демо-строчек... Внутри insertAfter → console.log(elem, refElem) ? 8 авг 2020 в 22:45
  • Не надо колбасить ДОМ руками во вложенном цикле по событию клика. Есть такая штука MVC (ru.wikipedia.org/wiki/Model-View-Controller). Есть куча библиотек на эту тему, например React. Есть методы коллекций, как map, filter, sort. 8 авг 2020 в 22:47

1 ответ 1

0

Используя es6 синтаксис, функция сортировки элементов может выглядеть так:

const sortNodes = (sortType, orderType = 'asc') => {
    const list = document.querySelector('#content');

    [...list.children]
        .sort((a, b)=> a.getAttribute(sortType) > b.getAttribute(sortType) ? 1 : -1)
        .forEach(node => orderType === 'asc' ? list.appendChild(node) : list.prepend(node))
}

Так же на eng-язычном stackoverflow довольно много материала по этой ссылке: https://stackoverflow.com/questions/282670/easiest-way-to-sort-dom-nodes

1
  • Спасибо, твой совет очень полезен, и очень помог мне.
    – Dmitry
    9 авг 2020 в 20:24

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.