创建一个新的jQuery链接方法 [英] Create a new jquery chained method

查看:105
本文介绍了创建一个新的jQuery链接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在jQuery中编写新的链接方法?我的jQuery有非常程序化的样式:

How do you write new chained methods in jQuery? I have a very procedural style in my jQuery:

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

如何在jQuery中创建.foo()方法,以便随后编写:

How do I create a .foo() method in jQuery so that I can then write:

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

与此相关的是-是否有一种简便的方法(在Visual Studio,Notepad ++或其他工具中)找到所有Foo($("#selector"));并将其替换为$("#selector").foo();?

And in a related point - is there an easy way (in Visual Studio, or Notepad++ or something else) to find and replace all Foo($("#selector")); with $("#selector").foo();?

推荐答案

您可以通过以下方式定义自定义jQuery函数:

You can define custom jQuery functions in this way:

$.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方法.

After this definition, every $("...") object will have a foo method.

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

If you're not sure whether the jQuery object is defined by a dollar, wrap your definiton in this function:

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

这篇关于创建一个新的jQuery链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆