写在前面
复习写插件的一些基本步骤。勿忘之。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery插件学习---1</title>
<script src="../../lib/jquery/jquery.js"></script>
</head>
<body>
<p id="para_1">this is a paragraph</p>
<button>button</button>
<p id="para_2">this is a paragraph</p>
<script>
(function ($) {
var defaults={
color:"red",
backgroundColor:"black",
trigger:"button"
};
var methods={
init:function (options) {
var settings=$.extend({},defaults,options)
return this.each(function () {
var $this=$(this);
$this.css({
color:settings.color,
backgroundColor:settings.backgroundColor
}).mouseover(function () {
//
});
$(settings.trigger).click(function () {
$this.fadeToggle(700);
});
});
}
};
$.fn.plugin_1=function () {
var method=arguments[0];
if(methods[method]){
method=methods[method];
arguments = Array.prototype.slice.call(arguments, 1);
} else if(typeof method==="object"||!method){
method=methods.init;
}else{
$.error("error happened!");
return this;
}
return method.apply(this,arguments);
};
})(jQuery);
$("#para_1").plugin_1({color:"blue",trigger:"#para_2",backgroundColor:"#aa0"});
</script>
</body>
</html>
defaults是默认参数。
methods是需要用到的函数集合。
settings是用户传入的参数和默认参数的融合。注意使用{}(空对象保存融合后的值,以保护默认参数)如果用户未指定参数,则使用默认值。否则,只要用户有一个传入的参数,则该参数使用用户值,其他使用默认值。
$.fn.plugin_name=function(){};
定义插件。
var method=arguments[0];
用来保存用户使用的函数(如果有的话)。
后面分别讨论用户传入的三种情况:函数,参数,或错误。
注意将插件包起来。
调用插件即可。