改进jQuery Button的代码

时间:2013-08-23 23:10:35

标签: javascript jquery html twitter-bootstrap

我刚刚开始使用JS和jQuery,我一直在尝试改进我正在使用的Bootstrap 3按钮的代码。

它有两个内部跨度,一个带有文本,另一个带有V形字体图标。

我想知道是否有办法优化我的代码(仅仅是为了学习)。

这是我的工作代码。

首先是HTML

<button type="button" class="btn btn-default btn-lg btn-imgs">
 <span class="btn-imgs-toggle">Ocultar Imágenes </span>                                      
 <span class="glyphicon glyphicon-chevron-up"></span> 
</button>

现在是jQuery:

$('.btn-imgs').click(function(){
    $('.thumbnail img').toggle();

    //variables
    var icono = $(this).children('.glyphicon');

    var $text = $(this).children('.btn-imgs-toggle');

    //cambia texto del boton
    $text.toggleClass('mostrar');

    //si el texto y el icono coinciden con un tipo cambialos al otro
    if( $text.hasClass('mostrar') && $(icono).is('.glyphicon-chevron-up')){
        $text.text('Mostrar imágenes');
        $(icono).removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
    } 

    else {
        $text.text('Ocultar imágenes');
        $(icono).removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
    }



});

非常感谢您对此提出的任何意见。我已经学习了很多其他已发布的问题。

1 个答案:

答案 0 :(得分:1)

就个人而言,我认为没有任何理由对孩子的状态进行仔细检查,除非你有其他脚本可以修改这些元素。此外,icono在您定义它时已经是一个jQuery对象,没有理由使用jQuery方法将其包装。

如果我写这篇文章,我会这样做:

$(body).on('click', '.btn-imgs', function(e) {
    e.preventDefault();
    $('.thumbnail img').toggle(); // how are you sure you are toggling the correct state?
    // I would consider including this in the conditional, but I don't know the purpose of
    // this, so I will leave it as is.
    $(this).find('.glyphicon').toggleClass('glyphicon-chevron-down glyphicon-chevron-up')
    .siblings('.btn-imgs-toggle').toggleClasS('mostrar').text(function () {
        return ($(this).hasClass('glyphicon-chevron-down') ? 'Mostrar' : 'Ocultar') + ' imágenes';
    });
});
相关问题