A typical plug-inCodeAs follows:
(Function($) {$. FN. mynewplugin=Function(){Return This. Each (Function(){//A bunch of code...}) ;};} (Jquery ));
Didn't you get dizzy with those lines of code? In fact, the focus is to extend the prototype object of jquery. See the following line:
$. FN. mynewplugin = function (){//...
Here we just put it inside a function that is instantly executed:
(Function ($) {//...} (jquery ));
This is to create a private scope. We can use $ extension jquery in this private scope securely without worrying that $ will be rewritten by other JS libraries.
Therefore, the actual plug-in code here is as follows:
$. FN. mynewplugin =Function(){Return This. Each (Function(){//A bunch of code...});};
Keywords in the new plug-inThis
It points to the jquery object that calls this plug-in.
VaRSomejqueryobject = $ ('# Something'); $. FN. mynewplugin=Function() {Alert (This===Somejqueryobject) ;}; somejqueryobject. mynewplugin ();//Alerts 'true'
A typical jquery object contains any number of DOM objects, which is why jquery objects are viewed as DOM object sets.
Therefore, you need to traverse the object set throughEach ()
This method is easy to implement.
$. FN. mynewplugin =Function(){Return This. Each (Function(){});};
Like other jquery methods,Each ()
The method also returns a jquery object, which makes it a well-known and beloved chain Writing Method ($(...).Css (). ATTR ()...
). We should not break this convention, so we should also returnThis
Object. Inside the loop, you can do what you want to do for every element. As discussed above, the following is an example of a small plug-in.
(Function($) {$. FN. showlinklocation=Function(){Return This. Filter ('A'). Each (Function() {$ (This). Append ('(' + $ (This). ATTR ('href ') + ')') ;}};}( Jquery ));//Example:$ ('A'). showlinklocation ();
This small plug-in can be usedHref
The property value is enclosed in parentheses and displayed as the content of the element.
<! -- Before calling the plug-in: --> <a href = "page.html"> Foo </a> <! -- And then: --> <a href = "page.html"> Foo (page.html) </a>
Although simple, this plug-in can be optimized as follows:
(Function($) {$. FN. showlinklocation=Function(){Return This. Filter ('A'). append (Function(){Return'(' +This. Href + ')';}) ;};} (Jquery ));
We used,Append
The method is to accept a callback function as a parameter and use the return value of the callback function as the content to be added. At the same time, we can also note thatATTR
Method To obtainHref
But directly uses the built-in dom api to access the element'sHref
Attribute.
The following is another example. It does not need to be used.Each ()
Method to traverse through loops, but simply delegates it directly to another jquery method:
(Function($) {$. FN. fadeinandaddclass=Function(Duration, classname ){Return This. Fadein (duration,Function() {$ (This). Addclass (classname) ;};}( jquery ));
// Usage: $ ('A'). fadeinandaddclass (400, 'finishedfading ');