jquery $.fn usage

$.fn refers to the namespace of jquery, plus the methods and attributes on fn, which are valid for each jquery instance. If $.fn.abc() is extended, that is, $.fn.abc() extends an abc method to jquery, then every subsequent instance of jquery can reference this method. Then you can do this: $( "#div").abc();

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

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

What is fn. Looking at the jQuery code, it's not hard to find. Copy the code The code is as follows:

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

It turns out that jQuery.fn = jQuery.prototype. is definitely not unfamiliar to prototype. jQuery is a very well encapsulated class. For example, we use the statement $("#btn1") to generate an instance of the jQuery class.

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

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

Then add a "static method" for add to jQuery, and then you can use this method where jQuery is introduced, $.add(3,4); //return 7

jQuery.fn.extend(object); The extension of 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, make a special edit box, when it is clicked, it will alert the content of the current edit box. Do this:

jQuery code copy code The code is as follows:

$.fn.extend({

alertWhileClick:function(){

$(this).click(function(){

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325469935&siteId=291194637