问题
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