jQuery插件的开发包括两种:一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数。
另一种是对象级别的插件开发,即给jQuery对象添加方法。
一. 基本概念
用JQuery写插件时,最核心的方法有如下两个:
$.extend(object) 可以理解为JQuery 添加一个静态方法。
$.fn.extend(object) 可以理解为JQuery实例添加一个方法
基本的定义与调用:
/* $.extend 定义与调用
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$.extend({ fun1: function () { alert("执行方法一"); } });
$.fun1();
/* $.fn.extend 定义与调用
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$.fn.extend({ fun2: function () { alert("执行方法2"); } });
$(this).fun2();
//等同于
$.fn.fun3 = function () { alert("执行方法三"); }
$(this).fun3();
jQuery(function () { }); 与 (function ($) { })(jQuery);的区别:
jQuery(function () { });
//相当于
$(document).ready(function () { });
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
(function ($) { })(jQuery);
//相当于
var fn = function ($) { };
fn(jQuery);
jQuery(function () { });是某个DOM元素加载完毕后执行方法里的代码。
(function ($) { })(jQuery); 定义了一个匿名函数,其中jQuery代表这个匿名函数的实参。通常用在JQuery插件开发中,起到了定义插件的私有域的作用。
代码:
<html>
<head><h>widget</h>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
(function ($) {
$.fn.sharePop = function () {
$(this).click(function(e){
e.preventDefault();
alert("1");
})
};
})(jQuery);
$(document).ready(function () {
$('a').sharePop();
$.fn.hilight.defaults.color = "red";
$(".div1").hilight();
});
(function ($) {
// plugin definition
$.fn.hilight = function (options) {
// Extend our default options with those provided.
var opts = $.extend({}, $.fn.hilight.defaults, options);
return this.each(function () {
//step06-b 在插件里定义方法
$(this).css(opts);
});
};
$.fn.hilight.defaults = { color: 'blue', background: 'yellow' };
})(jQuery);
//step01 定义JQuery的作用域
(function ($) {
//step03-a 插件的默认值属性
//var defaults = {
// "color": "red",
// "background-color":"blue"
//};
//step02 插件的扩展方法名称
$.fn.easySlider = function (options){
//step03-b 合并用户自定义属性,默认属性
var options = $.extend({}, $.fn.easySlider.defaults, options);
//step4 支持JQuery选择器
//step5 支持链式调用
return this.each(function () {
//step06-b 在插件里定义方法
$(this).css(options);
//showLink(this);
});
}
$.fn.easySlider.defaults = {
color: "white",
background: "blue"
}
})(jQuery);
</script>
</head>
<body>
<a class="div1" href="http://www.baidu.com">text</a>
<a href="http://www.baidu.com">click</a>
</body>
</html>