创建一个新的jquery链式方法

JK.*_*JK. 1 jquery jquery-plugins method-chaining

你如何在jQuery中编写新的链式方法?我的jQuery中有一个非常程序化的风格:

$("#SaveButton").click(function () {
    Foo($("#SubTotal"));
    Foo($("#TaxTotal"));
    Foo($("#Total"));
    Bar($("#SubTotal"));
    Bar($("#TaxTotal"));
    Bar($("#Total"));        
});
Run Code Online (Sandbox Code Playgroud)

如何在jQuery中创建一个.foo()方法,以便我可以编写:

$("#SaveButton").click(function () {
    $("#SubTotal,#TaxTotal,#Total").foo().bar();
});
Run Code Online (Sandbox Code Playgroud)

并在相关点-是否有一种简单的方法(在Visual Studio或记事本++或别的东西)来查找和替换所有Foo($("#selector"));$("#selector").foo();

Rob*_*b W 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.
    });
}
Run Code Online (Sandbox Code Playgroud)

在此定义之后,每个$("...")对象都将有一个foo方法.

如果您不确定jQuery对象是否由美元定义,请在此函数中包装您的定义:

(function($){
    //Within this wrapper, $ is the jQuery namespace
    $.fn.foo = function(){
        //...
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)