2011-10-06 2 views
5

내 함수는 데이터 특성을 기반으로 필터링 된 (배열) 항목 목록을 반환합니다. 나는이 작업을 수행하려면 어떻게이것을 체인화 가능한 jquery 함수로 만드는 방법은 무엇입니까?

filterSvcType("hosting").fadeOut(); 

을 :

$(document).ready(function(){ 
    function filterSvcType (svcType) { 
     var selectedServices = $("#service-list div"); 
     var chose = selectedServices.filter(function() { 
      return $(this).data("service-type") == svcType; 
     }); 

     console.log(chose);    
    } 
    filterSvcType("hosting");  
}); 

내가하고 싶은 것은 다음과 같이 호출입니다 :이 기능 체인 방식을 만들 수 있다면

나는 그것을 하시겠습니까?

답변

9

추가 할 필요가 console.log 호출 후 return chose;입니다.

그러나 당신은 또한 그런 다음 호출 할 수있는 jQuery 플러그인

(function($) { 
    $.fn.filterServiceType = function(svcType){ 
     return this.filter(function(){ 
      return $(this).data("service-type") == svcType; 
     }); 
    }; 
})(jQuery); 

에이를 돌 수 있었다 조금 더 jQueryish입니다

$('#service-list div').filterSvcType('hosting').fadeOut(); 

있다.

+0

굉장! 그것을 플러그인으로 바꾸는 방법을 알려주는 보너스 포인트. 그 일을 하려던 것뿐이었습니다. –

1

당신은 당신의 필터링 요소

$(document).ready(function(){ 
    function filterSvcType (svcType) { 
     var selectedServices = $("#service-list div"); 
     var chose = selectedServices.filter(function() { 
      return $(this).data("service-type") == svcType; 
     }); 
     return chose; 
     console.log(chose);    
    } 
    filterSvcType("hosting").fadeOut();  
}); 

이 모든 jQuery를 방법에 사용되는 것과 동일한 원칙을 반환 할 수 있습니다. 그들은 당신이 보낸 어떤 선택자 및/또는 컬렉션에 어떤 논리를 짓고 그 콜렉션을 돌려줍니다. 이제 할 수있는 일은 다음과 같습니다.

var filtered = filterSvcType("hosting"); 
filtered.fadeOut(); 

실제로 체인과 동일합니다.

Here's a quick test to show it in action

관련 문제