Home  >  Article  >  Web Front-end  >  Instructions for using extend and fn.extend of jquery_jquery

Instructions for using extend and fn.extend of jquery_jquery

WBOY
WBOYOriginal
2016-05-16 18:12:20855browse

jQuery provides two methods for developing plug-ins, which are:

Copy code The code is as follows:

jQuery.fn.extend(object);
jQuery.extend(object);


jQuery.extend(object); To extend the jQuery class itself. Add new to the class method.
jQuery.fn.extend(object); Add methods to jQuery objects.

What is fn. Looking at the jQuery code, it's not hard to find.

Copy code The code is as follows:

jQuery.fn = jQuery.prototype = {
 init: function(selector, context) {//.... 
  //......
};


Original jQuery.fn = jQuery.prototype. You are definitely no stranger to prototype.

Although JavaScript does not have a clear concept of classes, it is more convenient to use classes to understand it.
jQuery is a very well-encapsulated class. For example, if we use the statement $("#btn1"), an instance of the jQuery class will be generated.

jQuery.extend(object); Add a class method to the jQuery class, which can be understood as adding a static method. For example:
Copy code The code is as follows:

$.extend({
 add: function(a,b){return a b;}
});


will add a "static method" for jQuery. , use this method,
$.add(3,4); //return 7

jQuery.fn.extend(object); To extend jQuery.prototype, you can add it to the jQuery class "Member functions". Instances of the jQuery class can use this "member function".
For example, we want to develop a plug-in to create a special edit box. When it is clicked, the content in the current edit box will be alerted. You can do this:
Copy code The code is as follows:

$.fn.extend({
alertWhileClick:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
$("#input1").alertWhileClick(); //On the page:
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn