jquery 插件开发方式有三种,
1 $.extend() 相当于向jquery添加了静态函数
2.$.fn 向Jquery添加新的方法
3.
$.widget()
别人的帖子说使用$.fn是最常见的,第三种比较麻烦,怪我太懒没有试过。
下面开始抄袭别人的帖子了:
第一种方式
$.extend({
log:
function
(message) {
var
now =
new
Date(),
y = now.getFullYear(),
m = now.getMonth() + 1,
//!JavaScript中月分是从0开始的
d = now.getDate(),
h = now.getHours(),
min = now.getMinutes(),
s = now.getSeconds(),
time = y +
'/'
+ m +
'/'
+ d +
' '
+ h +
':'
+ min +
':'
+ s;
console.log(time +
' My App: '
+ message);
}
})
$.log(
'initializing...'
);
//调用
第二种方式
$.fn.myPlugin =
function
() {
//在这里面,this指的是用jQuery选中的元素
//example :$('a'),则this=$('a')
this
.css(
'color'
,
'red'
);
}
<ul>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
<p>这是p标签不是a标签,我不会受影响</p>
<script src=
"jquery-1.11.0.min.js"
></script>
<script src=
"jquery.myplugin.js"
></script>
<script type=
"text/javascript"
>
$(
function
(){
$(
'a'
).myPlugin();
})
</script>
第三种方式不介绍了,过程就是这么简单。
但是
为了让插件方便维护,插件慢慢的变大了,在$.fn.myPlugin东搞一下,西搞一下就不好了,咋办呢,
使用面向对象的方式
var
Beautifier =
function
(ele, opt) {
this
.$element = ele,
this
.defaults = {
'color'
:
'red'
,
'fontSize'
:
'12px'
,
'textDecoration'
:
'none'
},
this
.options = $.extend({},
this
.defaults, opt)
}
//定义Beautifier的方法
Beautifier.prototype = {
beautify:
function
() {
return
this
.$element.css({
'color'
:
this
.options.color,
'fontSize'
:
this
.options.fontSize,
'textDecoration'
:
this
.options.textDecoration
});
}
}
//在插件中使用Beautifier对象
$.fn.myPlugin =
function
(options) {
//创建Beautifier的实体
var
beautifier =
new
Beautifier(
this
, options);
//调用其方法
return
beautifier.beautify();
}
调用方式:
$(
function
() {
$(
'a'
).myPlugin({
'color'
:
'#2C9929'
,
'fontSize'
:
'20px'
});
})
到此为止,差不多了,但是使用这个插件定义对象,那么对象会被定义到window对象上,所以为了不让这种事情发生,我们使用匿名函数封装一下,对命名空间不会污染。
;(
function
($, window, document,undefined) {
//定义Beautifier的构造函数
var
Beautifier =
function
(ele, opt) {
this
.$element = ele,
this
.defaults = {
'color'
:
'red'
,
'fontSize'
:
'12px'
,
'textDecoration'
:
'none'
},
this
.options = $.extend({},
this
.defaults, opt)
}
//定义Beautifier的方法
Beautifier.prototype = {
beautify:
function
() {
return
this
.$element.css({
'color'
:
this
.options.color,
'fontSize'
:
this
.options.fontSize,
'textDecoration'
:
this
.options.textDecoration
});
}
}
//在插件中使用Beautifier对象
$.fn.myPlugin =
function
(options) {
//创建Beautifier的实体
var
beautifier =
new
Beautifier(
this
, options);
//调用其方法
return
beautifier.beautify();
}
})(jQuery, window, document);
第一个;是干啥的呢?你想啊,在调用你这个插件之前,如果js缺少了;咋办。。就像写sql语句的时候,占了两行是不是会多写一个空格。
第二个问题,undefined参数,为什么要有?为什么没有传该参数。这个是防止undefined被别人重新定义了,那我们这插件就有bug了。不传该参数,就是相当于传了一个undefined给它。