Home  >  Article  >  Web Front-end  >  jquery extend and fn.extend

jquery extend and fn.extend

巴扎黑
巴扎黑Original
2017-07-09 17:59:531258browse

jQuery provides two methods for developing plug-ins, namely:

jQuery.fn.extend(object);

##jQuery.extend(object);

jQuery .extend(object); extends the jQuery class itself. Adds new methods to the class.

jQuery.fn.extend(object); Add methods to jQuery objects.

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


##jQuery.fn = jQuery.prototype = {

##  init: function( selector , context ) {//.... 

##   //......

};

It turns out that jQuery.fn = jQuery.prototype. You will definitely be familiar with prototype.

Although

javascript

does not have a clear concept of class, 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:

$.extend({

 add:function(a,b){return a+b;}

});

Then add a "static method" called add for jQuery, and then you can introduce jQuery where , use this method,

$.add(3,4); //return 7

jQuery.fn.extend(object ); To extend jQuery.prototype is to add "member functions" to the jQuery class. 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:


Java code


    $. fn.extend({
  1. # alertWhileClick:function(){

  2.    

  3. ##                                                                                                                                          click(function(){

  4. ##

  5. alert($(this).val());

  6.                                                                                                                           

  7. ##      
  8. });     
  9. $(
  10. "#input1"

    ).alertWhileClick();

    //On the page For:
  11. #$("#input1") is a jQuery instance. When it calls member method alertWhileClick, it implements expansion. Every time it is clicked, it will pop up the current content in the editor. In the real development process, of course you will not make such a novice plug-in. In fact, jQuery provides rich operation documents, Events, CSS, Ajax , effect methods, and by combining these methods, more Niubility plug-ins can be developed.

The above is the detailed content of jquery extend and fn.extend. For more information, please follow other related articles on the PHP Chinese website!

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