JQ插件写(其实js插件也一样)

jQuery面向对象开发的模式使我们的jQuery代码看起来思路清晰,不但有利于复用,甚至对程序的性能起到优化作用,一个好的面向对象写法能够帮助你快速入门jQuery插件开发。

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>选项卡插件的写法</title>
<style>
#tab div{ width:200px; height:200px; border:1px #000 solid; display:none;}
#tab .active{ background:red;}
#tab2 div{ width:200px; height:200px; border:1px #000 solid; display:none;}
#tab2 .active{ background:red;}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
//自定义事件:
//beforeChange
//afterChange
//配置信息
$(function(){
$('#tab').tabs();
$('#tab2').tabs({
heads : ['体育','娱乐','新闻','视频'],
bodys : ['tab1体育','tab1娱乐','tab1新闻f','tab1视频'],
events : 'mouseover'
});
$('#tab2').on('beforeChange',function(){
alert( $('#tab2').find('div:visible').html() );
});
$('#tab2').on('afterChange',function(){
alert( $('#tab2').find('div:visible').html() );
});
});
//闭包写法 (注意前后加括号)
(function($){
function fnTab(ele, options){
this.$element = ele;
this.defaults = {
heads : ['1','2','3'],
bodys : ['1111111','2222222','3333333'],
events : 'click'
};
this.settings = $.extend({} , this.defaults , options);
}
fnTab.prototype.init = function(){
this.create();
this.bind();
}
fnTab.prototype.create = function(){
for(var i=0;i<this.settings.heads.length;i++){
var $input = $('<input type="button" value="'+ this.settings.heads[i] +'">');
if(i==0){
$input.attr('class','active');
}
this.$element.append( $input );
}
for(var i=0;i<this.settings.bodys.length;i++){
var $div = $('<div>'+ this.settings.bodys[i] +'</div>');
if(i==0){
$div.css('display','block');
}
this.$element.append( $div );
}
}
fnTab.prototype.bind = function (){
var that = this;
that.$element.find('input').on(this.settings.events,function(){
that.$element.trigger('beforeChange');
that.$element.find('input').attr('class','');
$(this).attr('class','active');
that.$element.find('div').css('display','none');
that.$element.find('div').eq( $(this).index() ).css('display','block');
that.$element.trigger('afterChange');
});
}
//在插件中使用Tab对象
$.fn.tabs = function(options) {
//创建Tab的实体
var Tab = new fnTab(this, options);
//调用其方法
return Tab.init();
}
})(jQuery);
</script>
</head>
<body>
<div id="tab">
<!--<input class="active" type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<div style="display:block">1111111</div>
<div>2222222</div>
<div>3333333</div>-->
</div>
<div id="tab2"></div>
</body>
</html>
文章目录
  1. 1. 代码如下
|