1. Start with a simple example, a method that does not require parameters
//Create an anonymous function
(function($){
//Add a new method to jQuery (see note 1 for details)
$.fn.extend({
//The name of the plug-in
MyFirstName: function() {
//Iterate the current matching element collection
return this.each(function() {
var obj = $(this);
//Your own code
});
}
});
)(jQuery);
Note 1: Understand $.fn.extend and $ The difference between .extend, roughly speaking, the former is to merge the MyFirstName method into the jquery instance object, for example, $("#txtmy").add(3,4) calls the method, and the latter is to merge the MyFirstName method into In the global object of jquery, for example $.add(3,4); This method is called
For details, see (
http://www.jb51.net/article/29590.htm)
2. With parameters
//Create An anonymous function
(function($){
//Attach a new method to jQuery (see note 1 for details)
$.fn.extend({
//The name of the plug-in
MyFirstName: function() {
//Define default parameters
Var parms={
Parms1:1,
Parms2:2
}
//Merge the parameters passed by the user and Default parameters, returned to options (see note 2 for details)
var options = $.extend(defaults, options);
//Iterate the current matching element collection
return this.each(function() {
//Assign the merged parameters to o
var o= options;
//Iterate the current matching element
var obj = $(this);
//Your own code
});
}
});
)(jQuery);
Note 2: var options = $.extend(defaults, options); means to replace defaults Merge with options. If the latter has an element with the same name as the former, the latter overwrites the former, and then merges it into defaults, and then defaults is assigned to options. If it is var options = $.extend({},defaults, options); then it is Merge the former and the latter into the {} parameter, and then assign it to options. The structure and value of defaluts remain unchanged
For detailed differences, please see (
http://www.jb51.net/article/29591.htm )
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