2013-08-23 40 views
0

我剛剛開始使用JS ans jQuery,我一直在嘗試改進我正在使用的Bootstrap 3按鈕的代碼。改進jQuery按鈕的代碼

它有兩個內部跨度,一個是文字,另一個是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'); 
    } 



}); 

非常感謝有這方面的投入。我一直在學習相當多的搜索其他發佈的問題。

+0

如果你想幫助優化其正常運行的代碼,你可能會考慮http://codereview.stackexchange.com –

+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'; 
    }); 
});