【问题标题】:Create a new jquery chained method创建一个新的 jquery 链式方法
【发布时间】:2026-01-12 03:10:01
【问题描述】:

如何在 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 或 Notepad++ 或其他东西中)找到所有 Foo($("#selector")); 并将其替换为 $("#selector").foo();

【问题讨论】:

    标签: jquery jquery-plugins method-chaining


    【解决方案1】:

    您可以通过这种方式定义自定义 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 对象是否由美元定义,请将您的定义包装在此函数中:

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

    【讨论】:

    • Thanks I'll tr​​y that .. I can see how to handle when the selector returns one match, I just have to use $(this).prop("x","y"); etc, but what do I do when the selector returns multiple matches ?
    • 当你说要换行时,你的意思是整个事情都将是$.fn.foo = (function($){ // etc })(jQuery);
    • 谢谢现在知道了,试试看。
    【解决方案2】:

    猜你需要在每个函数的末尾返回 $(this) 以使其可链接。

    使用 robw 编写的函数并返回 $(this)。

    【讨论】:

      最近更新 更多