2011-10-06 17 views
5

我的函數根據data屬性返回一個已過濾的(數組)項目列表。如何將它變成可鏈式jquery函數?

我想,如果我可以讓這個功能可鏈接:

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

我想要做的就是這樣稱呼它:

filterSvcType("hosting").fadeOut(); 

我該怎麼辦呢?

回答

9

所有你需要補充的是return chose;console.log電話後。

但你也可以變成一個jQuery插件

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

這點,你可以調用作爲

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

這是一個比較jQueryish。

+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