Create a new jquery chained method

跟風遠走 提交于 2019-12-22 00:55:02

问题


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"));        
});

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

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

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();?


回答1:


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.
    });
}

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

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);



回答2:


Guess you need to return $(this) at the end pf each function to make it chainable.

Use the function robw wrote and return $(this).



来源:https://stackoverflow.com/questions/7800355/create-a-new-jquery-chained-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!