1、首先要将插件代码包裹在
1.
(
function
($){
2.
/*代码从这里开始*/
3.
})(jQuery);
代码解释:(function(){})(),这句代码指的是创建一个匿名函数function(){}并立即执行, 并在参数中传入了jQuery对象,所以在代码中你就可以“$”使用jQuery对象,将代码放入匿名函数中的目的:在函数中定义的变量是局部变量,不会与全局变量冲突。
2、添加插件
添加插件通过
1.
$.fn.changeColor =
function
(){
2.
/*插件操作代码从这里开始
3.
this指当前jquery对象
4.
*/
this
.css(
'color'
,
'red'
);
5.
}
通过这句我们就添加了一个名叫changeColor的插件,这时任何jquery对象都可以使用这个插件了,使用方法例如,$('#test').changeColor(),这个插件实现的功能是将当前jquery对象的文本颜色改为red。
/*插件代码*/
(function($){
$.fn.changeColor = function(){
this.css('color','red');
}
})(jQuery);
实例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
/*插件代码*/
(function($){
$.fn.changeColor = function(){
this.css('color','red');
}
})(jQuery);
</script>
</head>
<body>
<span id="test">jquery插件开发教程</span>
<button οnclick="$('#test').changeColor()">变颜色</button>
</body>
</html>