2011-10-17 16 views
1

如何在jQuery中編寫新的鏈接方法?我有一個很程序風格在我的jQuery:創建一個新的jquery鏈接方法

$("#SaveButton").click(function() { 
    Foo($("#SubTotal")); 
    Foo($("#TaxTotal")); 
    Foo($("#Total")); 
    Bar($("#SubTotal")); 
    Bar($("#TaxTotal")); 
    Bar($("#Total"));   
}); 

如何創建jQuery中包含.foo()方法,這樣我就可以寫:

$("#SaveButton").click(function() { 
    $("#SubTotal,#TaxTotal,#Total").foo().bar(); 
}); 

並在相關點 - 是有一個簡單的方法(在Visual Studio中,或記事本++或其他)找到並替換所有Foo($("#selector"));$("#selector").foo();

回答

6

可以這樣定義自定義jQuery函數:

$.fn.foo = function(){ 
    //`this` is a jQuery object, referring to the matched elements (by selector) 
    return this.each(function(index, element){ 
     //`this` inside this function refers to the DOM element 
     var $this = $(this); //`this` is wrapped in a jQuery object. 
    }); 
} 

這個定義之後,每$("...")對象有一個foo方法。

如果你不知道的jQuery對象是否是由美元的定義,包你definiton在這個函數:

(function($){ 
    //Within this wrapper, $ is the jQuery namespace 
    $.fn.foo = function(){ 
     //... 
    } 
})(jQuery); 
+0

謝謝我會嘗試..當選擇器返回一個匹配時,我可以看到如何處理,我只需要使用'$(this).prop(「x」,「y」);'等,但當選擇器返回多個匹配時我該怎麼辦? –

+0

當你說打包時,你的意思是整個事情將是'$ .fn.foo =(function($){// etc})(jQuery);'? –

+0

@JK。看到我更新的答案。 –

1

猜你需要在最後返回$(本)pf的每個功能使其可鏈接。

使用函數robw寫入並返回$(this)。