Mejor forma de agregar / eliminar clases al hacer clic

I have two links, ".sp" and ".sl" when you click they change the visibility of some content ("#live") and ("#paid"), a low level type of tab interface i guess. I ad a class of 'active' on click and remove the class on the other link if it had it. This seems a bit bloated for such a small function, is there a better way to write this?

$(function() {
    $('#live').hide();
    $('.sp').click(function() {
        $(this).addClass('active');
        $('#paid').show();
        $('#live').hide();
        $('.sl').removeClass('active');
    });
    $('.sl').click(function() {
        $(this).addClass('active')
            $('#live').show();
            $('#paid').hide();
            $('.sp').removeClass('active');
    });
});

preguntado el 01 de febrero de 12 a las 03:02

2 Respuestas

Prueba con esto.

$(function() {
    $('#live').hide();
    var $links = $('.sp, .sl').click(function() {
        $links.removeClass('active');
        var isSp = $(this).addClass('active').hasClass('sp');
        $('#paid').toggle(isSp);
        $('#live').toggle(!isSp);
    });
});

Respondido 01 Feb 12, 08:02

@ShankarSangoli thats twice today. Your pretty bad ass. Thx again man. - Diseño de pájaro sucio

I'd suggest a utility function that can do the common work for you and be called both places.

$(function() {
    function clickCommon(current, newItem, oldItem, deactive) {
        $(current).addClass('active');
        $(newItem).show();
        $(oldItem).hide();
        $(deactive).removeClass('active');    
    }

    $('#live').hide();
    $('.sp').click(function() {
        clickCommon(this, "#paid", "#live", ".sl");
    });
    $('.sl').click(function() {
        clickCommon(this, "#live", "#paid", ".sp");
    });
});

Respondido 01 Feb 12, 08:02

just saw this, how is it better than the one above? seems like a bit more work? - Diseño de pájaro sucio

It's a bit of personal preference which one you prefer. I think this is a few more lines of code, but a little more direct to follow and a little more extensible if you had more than just .sp and .sl participating in the logic. Either would work fine in practice. I think too often when people are using these anonymous functions, they tend to forget that common code can just be factored out into a common function and used in multiple places so I thought it was worth sharing that option. - jfriend00

Very good point, in the end re using code is more efficient even if I have to write a little more. Thx! - Diseño de pájaro sucio

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.