5

私の関数は、データ属性に基づいてアイテムのフィルター処理された(配列)リストを返します。

この関数を連鎖可能にできるかどうかを教えてください。

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

どうすればよいですか?

4

2 に答える 2

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です。

于 2011-10-06T08:39:01.707 に答える
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();

これは、実際には連鎖と同じです。

これが実際の動作を示すための簡単なテストです

于 2011-10-06T08:39:00.803 に答える