2011-10-06 11 views
5

La mia funzione restituisce un elenco filtrato (array) di elementi in base all'attributo dati.Come posso trasformarlo in una funzione jquery concatenabile?

Mi piacerebbe se ho potuto fare questa funzione chainable:

$(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");  
}); 

Quello che voglio fare è chiamare in questo modo:

filterSvcType("hosting").fadeOut(); 

Come posso fare questo?

risposta

9

Tutto quello che dovete aggiungere è return chose; dopo la vostra console.log chiamata.

Ma si potrebbe anche trasformare questo in un plugin jQuery

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

Poi si può chiamare come

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

Che è un po 'più jQueryish.

+0

fantastico! punti bonus per avermi mostrato come trasformarlo in un plugin. Stavo solo cercando di farlo –

1

si può semplicemente restituire i vostri elementi filtrati

$(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();  
}); 

Questo è lo stesso principio che viene utilizzato su tutti i metodi di jQuery. Fanno alcune logiche a qualunque selettore e/o collezione che invii, e poi restituiscono quella collezione. Quindi ora puoi fare:

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

Che è lo stesso del concatenamento, davvero.

Here's a quick test to show it in action

Problemi correlati