转载于 http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html
demo1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul>
<li><a href="www.aa.com" class="a">aaa</a></li>
<li><a href="www.bb.com" class="b">bbb</a></li>
<li><a href="www.cc.com">ccc</a></li>
</ul>
</body>
</html>
<script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
;(function($,window,document,undefined){ //前面;防止前面js最后没有写;程序报错
$.fn.myPlugin = function(options){ // 写jQuery常见的方法
var defaults = { //设置默认参数
color: 'yellow',
fontSize: '14px'
};
var settings = $.extend({}, defaults ,options);
//用options覆盖defaults重名的属性
return this.css(settings);
// return 为了能够链式调用
}
})(jQuery,window,document); // 立即执行函数为了防止变量污染
</script>
<script type="text/javascript">
//面向对象的写法
;(function($,window,document){
var Beautify = function(mythis,opt){ //构造函数 里面主要写对象的属性
this.$element = mythis;
this.opt = opt;
this.defaults = {
color: 'red',
fontSize: '26px'
}
this.options = $.extend({},this.defaults,this.opt)
};
Beautify.prototype.plugin = function(){
return this.$element.css({
fontSize: this.options.fontSize,
color: this.options.color
});
}
$.fn.myPlugin = function(opt){
var obj = new Beautify(this,opt);
return obj.plugin();
}
})(jQuery,window,document);
</script>
<script type="text/javascript">
$('a.a').myPlugin({
color: 'red',
fontSize: '20px'
});
$('a.b').myPlugin();
</script>
本文介绍了使用 jQuery 开发插件的基本方法,包括如何创建插件、定义默认配置及覆盖选项,并通过具体示例展示了两种不同的插件实现方式。
3376

被折叠的 条评论
为什么被折叠?



