Javascript链式调用
所谓的链式调用无非是一个语法技巧而已,我就学Jquery写了一个粗浅的库。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5 <title>Javascript链式调用</title>
6 <script type="text/javascript">
7 function ele(){
8 this.elements=[];
9 var element;
10 if(typeof arguments[0]=="string"){
11 element=arguments[0];
12 if (element.slice(0, 1) == '#') {
13 element = document.getElementById(element.slice(1));
14 this.elements.push(element);
15 }else if(element.slice(0,1)=='.'){
16 element=element.slice(1);
17 var es = document.body.getElementsByTagName('*');
18 for (var i = 0, j = es.length; i < j; i++) {
19 if (element.indexOf(es[i].className) != -1) {
20 //alert(111);
21 this.elements.push(es[i]);
22 }
23 }
24 }else{
25 this.elements = document.getElementsByTagName(element);
26 //alert(elements[0].id);
27 }
28 }else{
29 element=this;
30 this.elements.push(element);
31 }
32 }
33 ele.prototype.each=function(fn){
34 for(var i=0,l=this.elements.length;i<l;i++){
35 fn.call(this,this.elements[i]);
36 }
37 return this;
38 };
39 ele.prototype.setStyle=function(prop,value){
40 this.each(function(el){
41 el.style[prop]=value;
42 });
43 return this;
44 };
45 ele.prototype.show=function(){
46 this.setStyle("display","block");
47 return this;
48 };
49 window.$=function(){
50 return new ele(arguments[0]);
51 };
52 </script>
53 </head>
54 <body>
55 <div id="test" class="ttt" style="width:100px; height:100px; background-color:red; display:none;"></div>
56 <div class="ttt" style="width:100px; height:100px; background-color:black; display:none;"></div>
57 <script type="text/javascript">
58 $('.ttt').setStyle('width','300px').show();
59
60 //$('#test').setStyle('width','300px').show();
61
62 //$('div').setStyle('width','300px').show();
63 </script>
64 </body>
65 </html>
posted on 2010-05-18 12:53 kingQueenyun 阅读(620) 评论(0) 编辑 收藏 举报