2013-08-23 2 views
0

JS ans jQuery로 시작하고 있으며 현재 작업중인 Bootstrap 3 버튼의 코드를 개선하려고 노력해 왔습니다.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'); 
    } 



}); 

덕분에 여기에 대한 입력에 대한 많은 다음 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와

첫째. 나는 다른 게시 된 질문을 통해 검색을 많이 배우는 중이 었어.

+0

, 당신은 http://codereview.stackexchange.com –

+0

감사를 고려해 볼 수 있습니다! 그것에 대해 몰랐어! –

답변

1

개인적으로 나는 이러한 요소를 수정할 다른 스크립트가 없다면 어린이의 상태에 대해 다시 확인해야 할 이유가 있다고 생각하지 않습니다. 또한 icono은 jQuery 객체를 정의 할 때 이미 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'; 
    }); 
});