2011-10-17 80 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)。