So let's start with a simple look at the most orthodox JQuery plugin definition:
?
1 2 3 4 5 6 7 8 9 10 11 12 |
(
function ($) { $.fn.插件名 =
function (settings) { //默认参数 var defaultSettings = {
}
/* 合并默认参数和用户自定义参数 */
settings = $.extend(defaultSettings, settings);
return this
.each(
function () {
//代码 }); //插件在元素内多次出现
} })(jQuery);
|
First look at the first line of code in the template (of course we want to look at the second half of this line of code, otherwise the first line is completely meaningless):
?
1 2 3 |
( function ($) { })(jQuery); |
This line of code is actually used to create an anonymous function. If you do not know about anonymous functions and closures, you will be very confused about this code, so it is highly recommended that you read the anonymous function and the closure of the function in JavaScript.
the method of inheriting JQuery $.extend--$.extend has a very important role in the development of jquery plug-ins, which is used for merging parameters.
?
1 2 3 4 5 6 7 8 9 |
$.fn.tip =
function (settings) { var defaultSettings = { //颜色 color:
‘yellow‘
, //延迟 timeout: 200 }
/* 合并默认参数和用户自定义参数 */
settings = $.extend(defaultSettings, settings); alert(settings.input); <br>}
|
The JQuery plugin defines the second way:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
(
function ($) {
//插件定义--更换名字
$.fn.tabpanel =
function (method) {
var methods = $.fn.tabpanel.methods;
if (methods[method]) {
return methods[method].apply(
this
, Array.prototype.slice.call(arguments, 1));
}
else if (
typeof method ===
‘object‘ || !method) {
return methods.init.apply(
this
, arguments);
}
else {
}
}
//支持的方法
$.fn.tabpanel.methods =
{
//初始化
init:
function (p_options) {
tabpanelBind(p_options,
this
);
},
add:
function (p_options) {
addTab(p_options,
this
);
tabpanelBind(p_options,
this
);
// debugger
} }
function add(p_options) {
var _defaults = {
id:
""
}
<br>
//内部实现略.........<br> return _index;
} <br>})(jQuery);<br><br>调用 $(
"#team"
).tabpanel(
‘add‘
,
""
);
|