Ejercicio parientes funcionalizado


$(function () {
    function creaBoton(clase, valor) {
        return '<input type="button" class="btn btn-success ' + clase + '" value="' + valor + '">';
    }
    function lista(elementos, valor) {
        var res = "<ul>";
        for (var i = 0; i < elementos; i++) {
            res += '<li>' + valor + '</li>';
        }
        return res + "</ul>";
    }
    function columna(ancho, elementos) {
        var columna = '<div class="col-sm-' + ancho + '">';
        columna += creaBoton('menos', '-');
        columna += creaBoton('mas', '+');
        columna += creaBoton('otros', '/\\');
        columna += creaBoton('otrosmenos', '\\/');
        columna += lista(elementos, "-");
        columna += "</div>";
        return columna;
    }
    function columnas(ncol, ancho, elementos) {

        var res = "";
        for (var i = 0; i < ncol; i++) {
            res += columna(ancho, elementos);
        }
        return res;

    }
    $('#nuevo').click(function () {

        $('#resultado').html(columnas(4, 3, 5));


        $('.menos').click(function () {

            //  $(this).siblings('ul').children().eq(0) .remove();
            //Buscamos los hermanos de tipo 'ul' y quitamos el último hijo
            $(this).siblings('ul').children().last().remove();
            //Si ya no hay más hijos deshabilitamos el botón
            if ($(this).siblings('ul').children().length === 0) {
                $(this).attr('disabled', 'disabled');
            }
        });
        $('.mas').click(function () {
            //Buscamos el hermano de tipo ul y añadimos un elemento
            $(this).siblings('ul').append('<li>-</li>');
            $(this).siblings('.menos').removeAttr('disabled');
        });
        $('.otros').click(function () {
            //Los hermanos de mi columna tienen listas 'ul' y añadimos un elemento
            $(this).parent().siblings().children('ul').append('<li>-</li>');
            $(this).parent().siblings().children('.menos').removeAttr('disabled');

        });
        $('.otrosmenos').click(function () {
            //Los hermanos de mi columna tienen listas 'ul' y añadimos un elemento
            $(this).parent().siblings().children('ul').each(function () {
                $(this).children().last().remove();
                if ($(this).children().length === 0) {
                    $(this).siblings('.menos').attr('disabled', 'disabled');
                }
            });


        });
    });
});

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos