强大的JQuery-自定义插件

====jQuery插件编写原则=====
1.命名 jQuery.<插件名>.js
2.插件内部,this指向的是当前选择器取得的JQuery对象,不是内部对象, 例如click(), 内部的this指向的是DOM元素
3.this.each可以遍历所有元素
4.插件头部加分号,防止压缩的时候出问题
5.采用闭包写法

;(function($){ //$是jQuery对象
/代码块/
})(jQuery);

=====jQuery.fn.extend()和jQuery.extend()区别=======

jQuery.fn.extend() 封装对象方法,例子如下

<html xmlns="http://www.w3.org/1999/xhtml">;
<head>
<title>extend : color</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
.a{
color : red;
}
</style>
<script type="text/javascript" src="../../scripts/jquery.js"></script>
<script type="text/javascript">
//插件编写
;(function($) {
jQuery.fn.extend({
"color":function(value){
return this.css("color",value);
}
});
})(jQuery);

//插件应用
$(function(){
    //查看第一个div的color样式值
    alert($("div").color()+"\n返回字符串,证明此插件可用。");  
    //把所有的div的字体颜色都设为红色
    alert( $("div").color("red")+"\n返回object证明得到的是jQuery对象。");
})
</script>

</head>
<body>
<div class="a">red</div>
<div style="color:blue">blue</div>
<div style="color:green">green</div>
<div style="color:yellow">yellow</div>

</body>
</html>

jQuery.extend()

扩展JQuery对象,封装全局函数,或者选择器插件,常用于设计插件的一系列默认参数,例子如下

var setting = {a:1,b:2,c:3}
var option = {a:9,b:8}
var newJSON = jQuery.extend(setting,option);
结果是newJSON = {a:9,b:8,c:3}

猜你喜欢

转载自blog.51cto.com/13765598/2120100