jquery对象级别插件的开发

来源:互联网 发布:mysql 禁止删除数据 编辑:程序博客网 时间:2024/06/01 10:59
<!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" />
<title>隔行换色</title>
<script src="jquery-2.0.3.js"></script>
<script src="tabColor.js"></script>
<style>
table{
width:400px;
width:960px;
border:1px solid #000;
border-collapse:collapse;
margin:0 auto;
text-align:center;
}
table tr th,table tr td{
border:1px solid #000;
}
.evenclass1{
background:#F00;
}
.oddclass1{
background:#0F0;
}
.current1{
background:#339;
}
.evenColor{
background:#0F0;
}
.oddColor{
background:#f00;
}
.hoverColor{
   background:#fff;
}
</style>
</head>


<body>
<table id="table">
    <tr>
        <th>姓名</th>
            <th>年龄</th>
            <th>身高</th>
            <th>性别</th>
        </tr>
        <tr>
        <td>张三</td>
            <td>20</td>
            <td>170</td>
            <td>男</td>
        </tr>
        <tr>
        <td>李四</td>
            <td>22</td>
            <td>180</td>
            <td>女</td>
        </tr>
        <tr>
        <td>王二</td>
            <td>29</td>
            <td>180</td>
            <td>女</td>
        </tr>
        <tr>
        <td>麻子</td>
            <td>14</td>
            <td>140</td>
            <td>男</td>
        </tr>
    </table>
<script>
$('#table').tabColor({ //为什么要这样子调用 其实$等于Jquery他们是个构造函数 实例化出来了对象 所以要用$(),然后$()这个函数里面有选择器方法 传入参数#table 所以写成$('#table') 插件里面的$.fn.tabColor 其实就是$.peototype.tabColor 给$的原型添加了方法 然后我们就通过$('#table').tabColor()调用它
evenColor:'evenColor',
oddColor:'oddColor',
mouseenters:'mouseenter',
mouseleaves:'mouseleave',
hoverColor:'hoverColor'
}).css({fontSize:'20px'}); //因为return this了 所以这里可以链试操作了
</script>
</body>

</html>


/* 
  @Author: JINGJIE
*/  
;(function($){ //这是jquery对象级别的插件开发
/*$.fn.extend({
tabColor:function(){
alert('我是第二种jquery对象级别开发'); //也可以用extend扩展jQ实例方法
}
}); */
$.fn.tabColor = function(options){//我是第一种jquery对象级别开发

var defaults = { // //各种参数,各种属性
evenColor:'evenColor',
oddColor:'oddColor',
mouseenters:'mouseenter',
mouseleaves:'mouseleave',
hoverColor:'hoverColor'
};

var options = $.extend(defaults,options); //$.extend把参数合并到options中参数和属性 覆盖和合并到 defaults 然后在赋给options 说直白点就是覆盖和合并 这样子的好处就是 我们就可以在html页面里面 随便命名属性值 覆盖他 就可以在不改变插件里面东西的情况下 修改参数

return this.each(function(){ // 这里为什么要用返回each呢  首先在JQ中,each是遍历一个数组,比如你$('.some')返回的不一定只是一个jq对象,有可能是个数组,好多个elements.所以return this.each(){}是把所有你索引的对象都作用到这个插件下.你若保证你的插件每次都只会用一个JQ对象,那么你可以直接return this.

//实现功能的代码
var _this = $(this); //获取这个对象 
_this.find('tr:even').addClass(options.evenColor); //偶数行
_this.find('tr:odd').addClass(options.oddColor);//奇数行

_this.find('tr').on(options.mouseenters,function(){//鼠标经过
$(this).addClass(options.hoverColor);
});
_this.find('tr').on(options.mouseleaves,function(){//鼠标经过
$(this).removeClass(options.hoverColor);
});

});
}
})(jQuery);

0 0
原创粉丝点击