Today, I have just learned how to create jquery plug-ins. I would like to summarize what others have written and my own experiences to facilitate the learning of other beginners, considering that those who want to learn how to create the jquery plug-in must know the advantages and versatility of the jquery plug-in, I will not talk about it here. First, we should start with a simple instance without a method with parameters.
The Code is as follows:
// Create an anonymous Function
(Function ($ ){
// Add a new method to jQuery (for details, see note 1)
$. Fn. extend ({
// Plug-in name
MyFirstName: function (){
// Iterate the current Matching Element Set
Return this. each (function (){
Var obj = $ (this );
// Your own code
});
}
});
) (JQuery );
Note 1: Understanding $. fn. extend and $. the difference between extend is that the former combines the MyFirstName method into the jquery instance object, for example, $ ("# txtmy "). add (3, 4) to call the method. The latter combines the MyFirstName method into the global object of jquery, for example, $. add (3, 4); call the method in this way
See For details (http://www.jb51.net/article/29590.htm)
2. Parameters
The Code is as follows:
// Create an anonymous Function
(Function ($ ){
// Add a new method to jQuery (for details, see note 1)
$. Fn. extend ({
// Plug-in name
MyFirstName: function (){
// Define default parameters
Var parms = {
Parms1: 1,
Parms2: 2
}
// Merge user-passed parameters and default parameters and return them to options (for details, see note 2)
Var options = $. extend (defaults, options );
// Iterate the current Matching Element Set
Return this. each (function (){
// Assign the merged parameter to o
Var o = options;
// Iterate the current Matching Element
Var obj = $ (this );
// Your own code
});
}
});
) (JQuery );
NOTE 2: var options = $. extend (defaults, options); combines ults and options. If the latter has an element with the same name as the former, the latter overwrites the former, and then merges it with defaults, then defaults is assigned to options. If it is var options = $. extend ({}, defaults, options); combines the former and the latter to the {} parameter, and then assigns the value to options. The structure and value of defaluts remain unchanged.
See For details (http://www.jb51.net/article/29591.htm)