Рекурсивно добавить или удалить класс в списке jquery - PullRequest
0 голосов
/ 28 сентября 2018

У меня есть список с флажками, которые могут неограниченно увеличиваться, например:

<ul>
<li class="tailor-children">
    <input type="checkbox" class="tailorCheckbox" name="id" id="1_12" value="1_12" checked="">
    <label class="1_12" for="1_12">Animals</label>
    <ul>
        <li>
            <input type="checkbox" class="tailorCheckbox" name="id" id="2_1" value="2_1" checked="">
            <label class="2_1" for="2_1">Mammals</label>
            <ul>
                <li>
                    <input type="checkbox" class="tailorCheckbox" name="id" id="3_1" value="3_1" checked="">
                    <label class="3_1" for="3_1">Carnivores</label>
                </li>
            </ul>
            <ul>
                <li>
                    <input type="checkbox" class="tailorCheckbox" name="id" id="3_2" value="3_2" checked="">
                    <label class="3_2" for="3_2">Rodents</label>
                </li>
            </ul>
        </li>
    </ul>
    <ul>
        <li>
            <input type="checkbox" class="tailorCheckbox" name="id" id="2_2" value="2_2" checked="">
            <label class="2_2" for="2_2">Reptiles</label>
        </li>
    </ul>
</li>

Мне нужна функция для динамического добавления или удаления классов, которая работала бы независимо от размерасписок.У меня есть только жестко закодированное решение, которое работает, но оно не является рекурсивным, и это беспорядок.

tailor.on('change', 'input[type="checkbox"]', function () {
        var checkbox = $(this);
        if (checkbox.prop('checked')) {
            checkbox.parent().find('label').removeClass("removedIcon");
            checkbox.parent().find('label').addClass("removeIcon");
            checkbox.prop('checked', true);
            checkbox.parent().parent().parent().children('label').removeClass("removedIcon");
            checkbox.parent().parent().parent().children('label').addClass("removeIcon");
            checkbox.parent().parent().parent().children('input').prop('checked', true);
            checkbox.parent().parent().parent().parent().parent().children('label').removeClass("removedIcon");
            checkbox.parent().parent().parent().parent().parent().children('label').addClass("removeIcon");
            checkbox.parent().parent().parent().parent().parent().children('input').prop('checked', true);
            checkbox.parent().parent().parent().parent().parent().parent().parent().children('label').removeClass("removedIcon");
            checkbox.parent().parent().parent().parent().parent().parent().parent().children('label').addClass("removeIcon");
            checkbox.parent().parent().parent().parent().parent().parent().parent().children('input').prop('checked', true);
        }
        else {
            checkbox.parent().find('label').removeClass("removeIcon");
            checkbox.parent().find('label').addClass("removedIcon");
            checkbox.parent().find('input').prop('checked', false);
            if (!checkbox.parent().parent().find('label').hasClass("removeIcon") && checkbox.parent().parent().siblings().find('.removeIcon').length == 0) {
                checkbox.parent().parent().parent().children('label').removeClass("removeIcon");
                checkbox.parent().parent().parent().children('label').addClass("removedIcon");
                checkbox.parent().parent().parent().children('input').prop('checked', false);
            }
            if (!checkbox.parent().parent().parent().parent().find('label').hasClass("removeIcon") && checkbox.parent().parent().parent().parent().siblings().find('.removeIcon').length == 0) {
                checkbox.parent().parent().parent().parent().parent().children('label').removeClass("removeIcon");
                checkbox.parent().parent().parent().parent().parent().children('label').addClass("removedIcon");
                checkbox.parent().parent().parent().parent().parent().children('input').prop('checked', false);
            }
            if (!checkbox.parent().parent().parent().parent().parent().parent().find('label').hasClass("removeIcon") && checkbox.parent().parent().parent().parent().parent().parent().siblings().find('.removeIcon').length == 0) {
                checkbox.parent().parent().parent().parent().parent().parent().parent().children('label').removeClass("removeIcon");
                checkbox.parent().parent().parent().parent().parent().parent().parent().children('label').addClass("removedIcon");
                checkbox.parent().parent().parent().parent().parent().parent().parent().children('input').prop('checked', false);
            }
        }
    });

Может кто-нибудь привести меня на правильный путь, пожалуйста?Пожалуйста, помогите мне понять, как упростить это рекурсивным и эффективным способом.

Спасибо

1 Ответ

0 голосов
/ 28 сентября 2018

Не уверен, что вы пытаетесь достичь, но я надеюсь, что этот код будет делать то, что вы стремитесь сделать

Js Fiddle

$(document).on('change', 'input[type="checkbox"]', function () {

        let checkbox = $(this);
        if (checkbox.prop('checked')) {
            checkbox.siblings('label').removeClass("removedIcon");
            checkbox.siblings('label').addClass("removeIcon");

            checkbox.parent('li').parents('li').each(function () {
                $(this).children(':checkbox').prop('checked', true);

                $(this).children(':checkbox').siblings('label').removeClass("removedIcon");
                $(this).children(':checkbox').siblings('label').addClass("removeIcon");
            });

        } else {
            checkbox.siblings('label').removeClass("removeIcon");
            checkbox.siblings('label').addClass("removedIcon");

            checkbox.parent('li').parents('li').each(function () {
                let childrenLength = $(this).children(':checkbox').length;
                if (childrenLength == 0) {
                    $(this).children(':checkbox').prop('checked', false);

                    $(this).children(':checkbox').siblings('label').removeClass("removeIcon");
                    $(this).children(':checkbox').siblings('label').addClass("removedIcon");
                }
            });

            checkbox.siblings('ul').each(function () {
                $(this).find(':checkbox').prop('checked', false);

                $(this).find(':checkbox').siblings('label').removeClass("removeIcon");
                $(this).find(':checkbox').siblings('label').addClass("removedIcon");
            });
        }
    });
...