码迷,mamicode.com
首页 > 其他好文 > 详细

一个类似于jq的小型库

时间:2016-06-21 01:05:58      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

本人写了一个类似于jq的小型库,不过只是写了部分方法而已。并没有jq那么全面,下面就介绍下有哪些方法可以使用

第一个是选择器,

选择器比较简单 只支持ID选择器 $(‘#id_name’)

                     Class选择器$(‘.class_name’)

                     标签选择器$(‘tag _name’)

并没有像jq那样拥有高级的选择器。

 

方法有

Js延迟加载

Ready     $(document).ready(function(){

            // 在这里写你的代码...

});

$(functoin(){

 

})

 

 

事件有

Click     $(‘div’).click(functoin(){

               Alert(1)

})

Dblclick   ,   mousedown  mouseup ,  mouseover , mousemove  mouseout  mousemove keypress   keydown keyup  change  reset  submit  hover

 

效果有

Show  hide   toggle

 

 

Css 有

Css   offset  width  height  position

 

属性有

Attr  val  html  addClass   removeAttr

 

筛选有

Eq   find    index  get   first  lastss

 

动画有

Animate  stop

 

文档处理有

Append  remove  empty

 

工具方法有

Trim  ajax  setPage(分页) extend inArray   parseJSON   isFunction   isEmpty

isNumeric  type

 

 

cq核心源码

 

  1 /*
  2   作者:姚观寿
  3   cq:类似于jq的一个小型库
  4   时间:2016.6.19
  5   
  6 */
  7 (function(window,undefined,document){
  8    var isIe678   =   (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE6.0")||
  9                            (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE7.0")||
 10                            (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0");
 11  
 12  function checkType(data_type){
 13        return  Object.prototype.toString.call(data_type);
 14      }    
 15 
 16  function myAddEvent(obj , sEv , fn){
 17    try{  // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
 18          obj.addEventListener(sEv,fn,false);
 19      }catch(e){
 20         try{  // IE8.0及其以下版本
 21                  obj.attachEvent(‘on‘ + sEv ,function(){
 22                           fn.call(obj);  
 23                     });
 24         }catch(e){  
 25                               // 早期浏览器
 26                            obj[‘on‘ + sEv] = fn;
 27          } 
 28     }
 29  } 
 30  
 31   function getTopOrLeft(obj,attr){
 32              var obj_attr = 0;
 33              while(obj){
 34                    obj_attr+=obj[attr];
 35                   obj=obj.offsetParent;
 36              }
 37              return   obj_attr;
 38           }  
 39  
 40  function getStyle(obj , attr){
 41         var new_attr;
 42       if(attr==‘opacity‘){
 43                  new_attr =  parseFloat((window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]));  
 44            }else{
 45                 new_attr =   parseInt(window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]);  
 46                } 
 47               if(isNaN(new_attr)){
 48                      new_attr = 0;
 49                   }
 50       return   new_attr;
 51  /* return  attr==‘opacity‘?parseFloat((window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr])):parseInt(window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]);     */
 52 }
 53 
 54 function forEach(obj , fn ){
 55     var i=0, len = obj.length;
 56     for(;i<len;i++){
 57            fn(i);
 58     }
 59 }
 60  function getByClassName(oParent,className){
 61          var  aEle = oParent.getElementsByTagName(‘*‘),
 62                 aResult = [];
 63              forEach(aEle,function(i){
 64                  if(aEle[i].className == className ){
 65                           aResult.push(aEle[i]); 
 66                     }
 67             }); 
 68             return  aResult;     
 69     }
 70 
 71 function CopyArr(arr){
 72           var newArr = [];
 73              forEach(arr , function( i ){
 74                         newArr.push(arr[i]);               
 75                     }); 
 76          return       newArr;
 77     }
 78 
 79 function getIndex( obj ){
 80  var sibing = obj.parentNode.children,
 81         index = null ;
 82         forEach(sibing , function(i){
 83                if(sibing[i] == obj ){
 84                   return  index = i-1;
 85                 }  
 86          });
 87          return index;
 88 }
 89  
 90 function Tween(value, prop, animation_attr) {
 91     //初始化
 92      this.elem    = animation_attr.elem;
 93     this.prop    = prop;
 94     this.easing  = "swing"; //动画缓动算法
 95     this.options = animation_attr.options;
 96      this.start   = this.now = this.get();
 97      this.end     = value;
 98      this.unit    = "px"
 99 }
100 
101 Tween.prototype = {
102      get: function() {
103         var computed = getStyle(this.elem, this.prop);
104          return parseFloat(computed);
105     },
106      run:function(percent){
107          var eased;
108          this.pos = eased = swing(percent);
109           this.now = (this.end - this.start) * eased + this.start;
110         
111           this.elem.style[this.prop] = this.now +this.unit;
112         return this;
113     }
114 }
115  
116  //动画算法
117 function swing(p) {
118      var tmpe = 0.5 - Math.cos(p * Math.PI) / 2; 
119      return tmpe
120 }
121 
122  Tween.prototype = {
123      get: function() {
124         var computed = getStyle(this.elem, this.prop);
125          return parseFloat(computed);
126     },
127      run:function(percent){
128          var eased;
129          this.pos = eased = swing(percent);
130           this.now = (this.end - this.start) * eased + this.start;
131      
132         if(this.prop=="opacity"){
133                          if(isIe678){
134                                  this.elem.style.filter=‘alpha(opacity:‘+(this.now*100)+‘)‘
135                             }else{
136                                 this.elem.style[this.prop] = this.now;
137                             }
138              }else{
139                   this.elem.style[this.prop] = this.now +this.unit;
140         }
141         return this;
142     }
143 }
144 
145  function AnimationFn(elem, properties, options,  fn){
146  /*    elem.timerId = null;
147      if (elem.timerId !=undefined && elem.timerId) {
148             return false;
149          }*/
150  
151      var animation_attr = {
152          elem            : elem,
153         props           : properties,
154         originalOptions : options,
155         options         : options,
156         startTime       : null,//动画开始时间
157         tweens          : []//存放每个属性的缓动对象,用于动画
158      }
159   
160     for (var k in properties) {
161           animation_attr.tweens.push( new Tween(properties[k], k, animation_attr));
162     }
163      animation_attr.startTime=AnimationFn.fxNow || createFxNow();
164      var tick = function() {
165          var currentTime = AnimationFn.fxNow || createFxNow();
166              remaining = Math.max(0, animation_attr.startTime + animation_attr.options.duration - currentTime),
167              temp = remaining / animation_attr.options.duration || 0,
168              percent = 1 - temp;
169          var index = 0,
170             length = animation_attr.tweens.length;
171           for (; index < length; index++) {
172               animation_attr.tweens[index].run(percent);
173         }
174 
175          if (percent <= 1 && length) {
176              return remaining;
177          } else {
178               return false;
179         }
180 
181     }
182      tick.elem = elem;
183     //tick.anim = animation_attr;
184       tick.fn  = fn;
185        AnimationFn.fx.timer(tick);
186 }    
187 
188  function createFxNow() {
189     setTimeout(function() {
190          AnimationFn.fxNow = undefined;
191     },0);
192      return (AnimationFn.fxNow = Date.now());
193 }
194    
195 AnimationFn.fx = {
196      timer: function(timer) {
197           AnimationFn.timer=timer;
198          if (timer()) {  //timer() 只是调用一个而已,就是说有这个动画时候就执行函数 返回一个false 或者是 remaining;
199             //开始执行动画 走这里
200             AnimationFn.fx.start();
201         }  
202     },
203      start: function() {
204         if (!AnimationFn.timer.elem.timerId) {
205              AnimationFn.timer.elem.timerId = setInterval(AnimationFn.fx.tick, 13);
206         }
207     },
208      stop:function(){
209       clearInterval(AnimationFn.timer.elem.timerId);
210           AnimationFn.timer.elem.timerId = null;
211            AnimationFn.timer.fn&&AnimationFn.timer.fn.call(AnimationFn.timer.elem );
212      },
213      tick: function() {
214         //不停的调用,直到定时器关闭
215           var timer,
216             i = 0;
217           AnimationFn.fxNow = Date.now();
218          if (!AnimationFn.timer()) {
219               AnimationFn.fx.stop();
220          }
221           AnimationFn.fxNow = undefined;
222     }
223 }
224  
225 function CQuery(vArg,chained_mode){
226  
227             this.elements = [];
228          switch(typeof vArg) {
229               case  ‘function‘:
230              
231                           myAddEvent(window , ‘load‘ , vArg);
232                         break;
233               case ‘string‘:
234                             switch(vArg.charAt(0)){
235                                    case ‘#‘:    //id
236                                         var obj = document.getElementById(vArg.substring(1));
237                                             this.elements.push(obj);
238                                           break;
239                                   case ‘.‘:    //class
240                                           var objs = getByClassName(document , vArg.substring(1));
241                                             this.elements = objs;
242                                           break; 
243                                  default:   //tagName
244                                            this.elements = document.getElementsByTagName(vArg);
245                                            break;
246                                }
247                        break;  
248                      
249                 case  ‘object‘:
250                        switch(checkType(vArg)){
251                                 case  "[object HTMLDocument]":
252                                           // this.elements =  window;
253                                           this.elements.push(window);
254                                           break;
255                                  default :       
256                                             this.elements.push(vArg);  break;
257                            }
258                   
259     }
260      return this === window&&new CQuery(vArg);
261  }
262  
263  CQuery.prototype = {
264               ev:function(event , fn){
265                    var this_elements = this.elements;
266                     forEach(this.elements,function(i){
267                             myAddEvent(this_elements[i] , event , fn);   
268                       });  
269                     new_CQuery.elements = this.elements;
270                     return new_CQuery;  
271             },
272             ready:function(fn){
273                    
274                        myAddEvent(window, ‘load‘ , fn);
275               },
276              click:function( fn ){
277                  return this.ev(‘click‘,fn);
278             },
279            dblclick : function( fn ){
280                   return this.ev(‘dblclick‘,fn);
281                },
282            mousedown : function( fn ){
283                   return this.ev(‘mousedown‘,fn);
284                },  
285            mouseup : function( fn ){
286                    return this.ev(‘mouseup‘,fn);
287                },
288            mouseover : function( fn ){
289                  return this.ev(‘mouseover‘,fn);
290                }, 
291            mousemove : function( fn ){
292                  return this.ev(‘mousemove‘,fn);
293                },  
294            mouseout : function ( fn ){
295                   return this.ev(‘mouseout‘,fn);
296                },  
297            mousemove:function(fn){
298                return  this.ev(‘mousemove‘,fn);
299             },
300            keypress:function( fn ){
301                return  this.ev(‘keypress‘,fn);
302             },
303            keydown : function( fn ){
304                  return  this.ev(‘keydown‘,fn); 
305                },
306           keyup : function( fn ){
307                  return  this.ev(‘keyup‘,fn); 
308                },
309            change : function( fn ){
310                  return  this.ev(‘change‘,fn); 
311                },    
312            reset : function( fn ){
313                  return  this.ev(‘reset‘,fn); 
314                },    
315            submit : function( fn ){
316                  return  this.ev(‘submit‘,fn); 
317                },    
318             show:function(){
319                  var this_elements=this.elements;
320                 forEach(this.elements,function(i){
321                       this_elements[i].style.display = ‘block‘;
322                 });  
323                    new_CQuery.elements =  this.elements;
324                     return new_CQuery; 
325            },
326            hide:function(){
327                  var this_elements = this.elements ;
328                   forEach(this.elements,function(i){
329                        this_elements[i].style.display = ‘none‘;
330                 });  
331                  new_CQuery.elements =  this.elements;
332                   return new_CQuery;  
333            },
334            hover:function(fnOver , fnOut){
335                  var this_elements = this.elements ;
336                forEach(this.elements,function(i){
337                     myAddEvent(this_elements[i] , ‘mouseover‘ , fnOver);
338                     myAddEvent(this_elements[i] , ‘mouseout‘ , fnOut);    
339                });
340                  new_CQuery.elements =  this.elements;
341                   return new_CQuery; 
342            },
343            css:function(attr , value){
344               if(arguments.length==2){  //设置样式
345                  var  this_elements = this.elements
346                    forEach(this.elements , function(i){
347                                if(attr!=‘opacity‘){
348                                       this_elements[i].style[attr] = value; 
349                                  }else{
350                                       this_elements[i].style[attr] = value;
351                                  }
352                     });  
353               }else{   //获取样式
354                        return     getStyle(this.elements[0] , attr);
355               }
356                      new_CQuery.elements =  this.elements;
357                     return new_CQuery; 
358               },
359            toggle:function(){ 
360                      var  argm = arguments,
361                           argmLen = arguments.length,
362                           this_elements = this.elements ;
363                       forEach(this.elements,function(i){
364                                            var count = 0;              
365                                           myAddEvent(this_elements[i] , ‘click‘ , function(){
366                                            argm[count++%argmLen].call(this);
367                                                                                       })    ;
368                                     });   
369                     new_CQuery.elements =  this.elements;
370                      return new_CQuery; 
371                },
372                attr:function( attr , value){
373                          var    this_elements = this.elements ;
374                            if(arguments.length==2){
375                               forEach(this.elements , function( i ){
376                                         this_elements[i][attr] =  value;
377                              });
378                               new_CQuery.elements =  this.elements;
379                                return new_CQuery; 
380                           }else{
381                                           return this.elements[0][attr];
382                           }
383                },
384                eq:function( n ){
385                    return $(this.elements[n]); 
386                },
387                 find:function(str){
388                       var  aResult = [] ,
389                              this_elements = this.elements;
390                       forEach(this.elements , function( i ){
391                                       switch(str.charAt(0)){
392                                             case ‘.‘ :  //class
393                                                   var aEle = getByClassName(this.elements[i] , str.substring(1));
394                                                   aResult = aResult.concat(aEle);
395                                                   break;
396                                            default :
397                                                 var aEle = this_elements[i].getElementsByTagName(str);
398                                                        aResult = aResult.concat(CopyArr(aEle));
399                                           }
400                              }); 
401                      new_CQuery.elements = aResult;
402                     return new_CQuery;  
403                    },
404                    index : function(){
405                          return getIndex(this.elements[0]);
406                    },
407 
408                    offset:function(){
409          
410                                  if(arguments.length==0){
411                                    var offset={
412                                                          top:getTopOrLeft(this.elements[0],‘top‘),
413                                                          left:getTopOrLeft(this.elements[0],‘left‘)
414                                                       }
415                                     return      offset;                  
416                                 }else{
417                                            var this_elements = this.elements ;
418                                            forEach(this.elements,function(i){
419                                                      this_elements[i].style.left = arguments.length[0].left;
420                                                       this_elements[i].style.top = arguments.length[0].top;
421                                            });
422                                              new_CQuery.elements =  this.elements;
423                                              return new_CQuery;  
424                                          
425                                      }
426                                     
427                        },
428                       position:function(){
429                                  if(arguments.length==0){
430                                    var offset={
431                                                          top:this.elements[0].offsetTop,
432                                                          left:this.elements[0].offsetLeft
433                                                       }
434                                     return      offset;                  
435                                 }else{
436                                            var this_elements = this.elements ;
437                                            forEach(this.elements,function(i){
438                                                      this_elements[i].style.left = arguments.length[0].left;
439                                                       this_elements[i].style.top = arguments.length[0].top;
440                                            });
441                                              new_CQuery.elements =  this.elements;
442                                              return new_CQuery;  
443                                          
444                                      }
445                                     
446                        },
447                        
448                        
449                        
450                    animate:function(prop, speed, easing, callback){
451                                var _arguments = arguments;
452                               this_elements = this.elements;
453                                if(checkType(arguments[1])=="[object Undefined]"){
454                                               _arguments[1] = 400; 
455                                              forEach(this.elements , function( i ){
456                                                  AnimationFn(this_elements[i],_arguments[0], {
457                                                         duration: _arguments[1]
458                                                         }) 
459                                          });  
460                                   }else if ((checkType(arguments[1])=="[object String]"||checkType(arguments[1])=="[object Number]")&&checkType(arguments[2])=="[object Undefined]"){
461                                         
462                                               switch(arguments[1]){
463                                                            case   ‘slow‘ :    _arguments[1] = 600 ;  break;
464                                                            case  ‘normal‘:  _arguments[1] = 400;   break;
465                                                            case  ‘fast‘ :   _arguments[1] = 200; break;
466                                                            default :   if(checkType(arguments[1])=="[object String]"){
467                                                                                      _arguments[1] = 400;   
468                                                                                } break;                 
469                                                   }
470                                          forEach(this.elements , function( i ){
471                                                  AnimationFn(this_elements[i],_arguments[0], {
472                                                             duration: _arguments[1]
473                                                         }) 
474                                           });                                            
475                                       }else if((checkType(arguments[1])=="[object String]"||checkType(arguments[1])=="[object Number]"&&checkType(arguments[2])=="[object Undefined]")&&checkType(arguments[2])=="[object Function]"){
476                                              
477                                                  var _speed = 0;
478                                                   switch(arguments[1]){
479                                                            case   ‘slow‘ :    _speed = 600 ;  break;
480                                                            case  ‘normal‘:  _speed = 400;   break;
481                                                            case  ‘fast‘ :   _speed = 200; break;
482                                                            default :  
483                                                              if(checkType(arguments[1])=="[object String]"){
484                                                                                      _speed = 400; 
485                                                                                } break;                 
486                                                   }
487                                                    forEach(this.elements , function( i ){
488                                                         AnimationFn(this_elements[i],_arguments[0], {
489                                                                     duration: _speed
490                                                                 },_arguments[2]) 
491                                                        });              
492                                           }else if(checkType(arguments[1])=="[object Function]"){
493                                              
494                                                var _speed  = 400; 
495                                              forEach(this.elements , function( i ){
496                                                  AnimationFn(this_elements[i],_arguments[0], {
497                                                         duration: _speed
498                                                         },_arguments[1]) 
499                                          });  
500                                   }
501                            new_CQuery.elements = this.elements;
502                            return new_CQuery;            
503                          },
504                        stop:function(){
505                                  var this_elements = this.elements;
506                                 forEach(this.elements , function( i ){
507                                           if(this_elements[i].timerId){
508                                                    clearInterval(this_elements[i].timerId);
509                                                    this_elements[i].timerId= null;
510                                               }
511                                         });  
512                                new_CQuery.elements = this.elements;
513                                return new_CQuery;      
514                            },
515                         append:function(html){
516                                  var this_elements = this.elements;
517                                  forEach(this.elements , function( i ){
518                                              this_elements[i].innerHTML+=html;
519                                         });  
520                                new_CQuery.elements = this.elements;
521                                return new_CQuery;       
522                             },
523                             remove:function(){
524                              var this_elements = this.elements;
525                                  forEach(this.elements , function( i ){
526                                              this_elements[i].parentNode.removeChild(this_elements[i]); 
527                                         });  
528                                new_CQuery.elements = this.elements;
529                                return new_CQuery;       
530                                  },
531                                 empty:function(){
532                                 var this_elements = this.elements;
533                                  forEach(this.elements , function( i ){
534                                               for(var j=0, length = this_elements[i].children.length; j<length;j++){
535                                                       this_elements[i].removeChild(this_elements[i].children[j]); 
536                                                  }
537                                         });  
538                                new_CQuery.elements = this.elements;
539                                return new_CQuery;       
540                                       },
541                             get:function(index){
542                                     return this.elements[index];
543                                 },
544                                 val:function(){
545                                        if(arguments.length==0){
546                                             return  this.elements[0].value;
547                                          }else{
548                                                   var this_elements = this.elements;
549                                                   var _arguments = arguments;
550                                                    forEach(this.elements , function( i ){
551                                                        this_elements[i].value = _arguments[0];
552                                                   });  
553                                            new_CQuery.elements = this.elements;
554                                            return new_CQuery;        
555                                              }
556                                     },
557                                     html:function(){
558                                             if(arguments.length==0){
559                                             return  this.elements[0].innerHTML;
560                                          }else{
561                                                   var this_elements = this.elements;
562                                                   var _arguments = arguments;
563                                                    forEach(this.elements , function( i ){
564                                                        this_elements[i].innerHTML = _arguments[0];
565                                                   });  
566                                            new_CQuery.elements = this.elements;
567                                            return new_CQuery;        
568                                              }
569                                         },
570                                         addClass:function(class_name){
571                                                 var this_elements = this.elements;
572                                                  forEach(this.elements , function( i ){
573                                                        this_elements[i].className += ‘ ‘+class_name;
574                                                   });  
575                                                    new_CQuery.elements = this.elements;
576                                                  return new_CQuery;        
577                                             },
578                                     removeAttr:function(attr){
579                                      var this_elements = this.elements;
580                                          forEach(this.elements , function( i ){
581                                                 delete this_elements[i].attr;
582                                           });  
583                                            new_CQuery.elements = this.elements;
584                                          return new_CQuery;         
585                                         },
586                                         first:function(){
587                                               return  this.elements[0];
588                                             },
589                                     last:function(){
590                                         return  this.elements[this.elements.length-1];
591                                         },
592                                     height:function(){
593                                         if(arguments.lengt==0){
594                                               return   getStyle(this.elements[0],‘height‘);
595                                         }else{
596                                                   var this_elements = this.elements;
597                                                      forEach(this.elements , function( i ){
598                                                                this_elements[i].style.height = arguments[0]; 
599                                                       });  
600                                                        new_CQuery.elements = this.elements;
601                                                      return new_CQuery;   
602                                             }
603                                         },
604                                    width:function(){
605                                                    if(arguments.lengt==0){
606                                               return   getStyle(this.elements[0],‘width‘);
607                                         }else{
608                                                   var this_elements = this.elements;
609                                                      forEach(this.elements , function( i ){
610                                                                this_elements[i].style.width = arguments[0]; 
611                                                       });  
612                                                        new_CQuery.elements = this.elements;
613                                                      return new_CQuery;   
614                                             }
615                                       }                
616                                                  
617  }
618  
619  CQuery.trim = function(str){
620           return str.replace(/(^\s*)|(\s*$)/g, ""); 
621      }
622 CQuery.ajax = function(ajaxObj){
623                          if(ajaxObj.url==undefined){
624                                     alert(‘您未设置url,请您设置提交的url‘) ; 
625                                     return false;
626                         };
627  
628                         //设置json数据或者文件
629                          (ajaxObj.async!==undefined)||((ajaxObj.async===false)||(ajaxObj.async = true));
630                         
631                             ajaxObj.dataType=(ajaxObj.dataType===undefined)?‘json‘:( ajaxObj.dataType = ajaxObj.dataType.toLowerCase( ), (ajaxObj.dataType== ‘file‘&&‘flie‘)||(‘json‘));
632                     //设置post或者get方式  
633                      ajaxObj.type = (ajaxObj.type===undefined)?‘post‘:(ajaxObj.type =ajaxObj.type.toLowerCase( ),(ajaxObj.type==‘get‘&&‘get‘)||(‘post‘));         
634                  
635        var  submit_url = ‘‘,
636              submit_table_data=‘‘;
637              str=ajaxObj.url; //这是一字符串
638              var strs= new Array(); //定义一数组
639              strs=str.split("?"); //字符分割 
640              submit_url =  strs[0]; 
641          //设置清理缓存            
642 ajaxObj.cache = (ajaxObj.cache===undefined)?true:(ajaxObj.cache&&true||false); //缓存    
643         if(!ajaxObj.cache)    {
644                time = ‘time=‘+new Date().getTime();
645              submit_table_data = (strs.length<=1)?time:(time+‘&‘);
646               for(var i=1, len = strs.length; i<len ;i++ ){
647                       submit_table_data += (i==len-1)?strs[i]:(strs[i]+‘?‘);
648                   }
649            }else{
650                             for(var i=1, len = strs.length; i<len ;i++ ){
651                                  submit_table_data += (i==len-1)?strs[i]:(strs[i]+‘?‘);
652                               }     
653                           (submit_table_data==‘‘)||(submit_table_data+=‘&‘);
654                      }
655                       
656                       //数据连接
657                  switch(checkType(ajaxObj.data)){
658                      case "[object String]":
659                                 submit_table_data += ajaxObj.data;
660                                 break;    
661                      case "[object Object]":    
662                                 var submit_key = [],
663                                       submit_data = [];
664                                for(i in ajaxObj.data){
665                                        submit_key.push(i);
666                                        submit_data.push(ajaxObj.data[i]);
667                                    }
668                             //ajaxObj.url+=re.exec(ajaxObj.url)?"&":"?";
669                             forEach(submit_data , function(index){
670                                      submit_table_data+=((submit_data.length-1)==index)?submit_key[index]+‘=‘+submit_data[index]:submit_key[index]+‘=‘+submit_data[index]+‘&‘;
671                                 } )    ;  
672                  }
673 
674            //创建 xhr对象
675             if(window.XMLHttpRequest){
676                   var xhr=new XMLHttpRequest();
677                 } else{
678                  var xhr=new ActiveXObject("Microsoft.XMLHTTP");
679                }
680                
681            //数据
682            var fileLen=fileNumber=0;
683                  if(ajaxObj.type==‘get‘){
684                             if(ajaxObj.dataType== ‘flie‘){
685                                    alert(‘文件上传需要设置post提交!‘);
686                                 }
687                               xhr.open(‘get‘,submit_url+‘?‘+encodeURI(submit_table_data),ajaxObj.async);
688                               xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
689                               xhr.send();
690                      }else{
691                      
692                                 if(ajaxObj.dataType!=‘flie‘){
693                                             xhr.open(‘post‘,submit_url,true);
694                                             xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
695                                             // alert(ajaxObj.data);
696                                             xhr.send(submit_table_data);
697                                     }else{
698                                              if(ajaxObj.fileObject===undefined){
699                                                    alert(‘未设置文件对象,需要传递一个文件对象进来‘);
700                                                    return ;
701                                                 }
702                                                 
703                                                xhr.open("post",ajaxObj.url,ajaxObj.async);
704                                               //设置数据类型
705                                               xhr.setRequestHeader(‘X-Requested-With‘,‘XMLHttpRequest‘);         
706                                               //文件表单对象
707                                                var form = new FormData();  
708                                             
709                                               if(ajaxObj.fileObject.nodeName==‘INPUT‘){
710                                                     var file_name=  ajaxObj.fileObject.name;
711                                                      
712                                                   }else{
713                                                            var file_name =  (ajaxObj.fileName===undefined)?‘file‘:ajaxObj.fileName;
714                                                         }
715                                           //文件对象
716                                                fileObjs=ajaxObj.fileObject.files, 
717                                               fileLen=fileObjs.length;
718                                                form.append(file_name,fileObjs[0]);
719                                               xhr.send(form);
720                                           } 
721                          }
722                  
723     //响应监控
724 xhr.onreadystatechange=function (){
725                                                                                                           //  alert(‘正在加载数据‘);
726   (xhr.readyState!=1&&xhr.readyState!=2&&xhr.readyState!=3)||(ajaxObj.loading&&ajaxObj.loading(xhr.readyState),
727                                                                                                    ajaxObj.complete&&ajaxObj.complete(xhr)
728                                                                                                            );
729                        (xhr.readyState!=4)||((xhr.status==200)?(
730                                                                 // 返回ajax数据给前端alert(xhr.responseText);
731                                                                   ajaxObj.success&&ajaxObj.success(xhr.responseText),
732                                                                  //判断是否有多个文件,如果有多个文件再次提交
733                                                                    (fileNumber>(fileLen-1))||( 
734                                                                                                       fileNumber++,
735                                                                                                       xhr.open("post",submit_url,ajaxObj.async),
736                                                                                                       //设置数据类型
737                                                                                                        xhr.setRequestHeader(‘X-Requested-With‘,‘XMLHttpRequest‘),    
738                                                                                                        form.append(file_name,fileObjs[fileNumber]),
739                                                                                                        xhr.send(form)
740                                                                                                        )
741                                                                  ):(ajaxObj.complete&&ajaxObj.complete(xhr),
742                                                                    ajaxObj.error&&ajaxObj.error(xhr)
743                                                                    ))
744                                            
745                              
746                    }             
747                  
748    }
749 
750 
751 CQuery.setPage = function (page_arguments){
752               //获取到初始化数据
753               var id = page_arguments.id ,   //容器
754                      count = page_arguments.count ,    //总数
755                      now_index = page_arguments.index ,  //当前的索引
756                      success = page_arguments.success  ;   //成功之后的回调函数
757                       // control = (page_arguments.control !== undefined)?page_arguments.control:true;
758                      id.className = ‘page‘;
759                var  a =new Array();
760                      //初始化数据 第一个按钮的数据
761                  if(now_index == 1){
762                         a.push("<a href=‘javascript:‘ class=‘unclick‘>prev</a>");
763                      }else{
764                          a.push( "<a href=‘javascript:‘ >prev</a>");   
765                          }     
766                 //初始化中间的数据
767                 function setPageList(i,n_inx){
768                         if(i == n_inx){
769                                 a.push("<a href=‘javascript:‘ class=‘on‘ >"+i+"</a>");
770                             }else{
771                                  a.push("<a href=‘javascript:‘ >"+i+"</a>");
772                              }
773                     }
774              
775   function trim(str) {
776 
777     return str.replace(/(^\s*)|([^0-9])|(\s*$)/g,‘‘);
778 }
779              
780             function  forEach(start, end, fn){
781                      for(var i = start;  i <= end; i++){
782                               fn&&fn( i );
783                          }
784                 }    
785                 //中间的1到count 中的页数    
786                  if(count<=9){
787                      //这里只有一种情况
788                       forEach(1, count, function(i){
789                              setPageList(i,now_index);
790                           })
791                      }else{
792                              //这里有三种情况
793                              if(now_index<=4){
794                                        forEach(1, 5, function(i){
795                                                  setPageList(i,now_index);
796                                            });
797                                          a.push("...<a href=‘javascript:‘‘‘>"+count+"</a>");  
798                                  }else if(now_index >= (count-3)){
799                                              a.push("<a>"+1+"</a>..."); 
800                                             forEach(count-4, count, function(i){
801                                                  setPageList(i,now_index);
802                                            });
803                                      }else{
804                                              a.push("<a href=‘javascript:‘>1</a>..."); 
805                                              forEach(now_index-2,now_index+2,function(i){
806                                                     setPageList(i,now_index);
807                                                  });
808                                              a.push("...<a href=‘javascript:‘>"+count+"</a>");
809                                          }
810                         }
811                 //最后添加的按钮
812              
813                 if(now_index == count){
814                        a.push("<a href=‘javascript:‘ class=‘unclick‘>next</a>");
815                     }else{ 
816                         a.push("<a href=‘javascript:‘>next</a>");
817                      }        
818                      
819                 //到第几页
820                 a.push("<a  class=‘no‘>到第</a>");
821                 a.push("<a   class=‘no‘><input/ type=‘text‘></a>");
822                 a.push("<a  class=‘no‘>页</a>");
823                 a.push("<a href=‘javascript:‘>确定</a>");
824                 
825                 id.innerHTML = a.join(‘‘); 
826                 //添加事件
827                 var o_a = id.getElementsByTagName(‘a‘);
828                 for(var i = 0, len = o_a.length; i < len;  i++){
829                                     o_a[i].onclick = (function(i){
830                                              if(i==0){
831                                                           return function(){
832                                                                /* if(page_arguments.motion){
833                                                                         if(control){return false;}
834                                                                 }*/
835                                                                   now_index--;
836                                                                 if(now_index < 1 ){
837                                                                     now_index = 1;
838                                                                     return false ;
839                                                                     }
840                                                                 page_arguments.index = now_index;
841                                                                 //page_arguments.control = control;
842                                                                 CQuery.setPage(page_arguments);
843                                                                 success({count:count, index:now_index});
844                                                                 return false;
845                                                               }
846                                                  }else if(i == (len-5)){
847                                                          return function(){
848                                                                /*   if(page_arguments.motion){
849                                                                         if(control){return false;}
850                                                                 }*/
851                                                                 now_index++;
852                                                                if(now_index > count ){
853                                                                      now_index = count; 
854                                                                      return false ;
855                                                                    }
856                                                                 page_arguments.index = now_index;
857                                                               // page_arguments.control = control;
858                                                                CQuery.setPage(page_arguments);
859                                                                success({count:count, index:now_index});
860                                                                return false;
861                                                              }
862                                                      }else if(i == (len-4)){
863                                                          return function(){
864                                                                // alert(i)
865                                                              }
866                                                           }else if(i == (len-3)||i == (len-2)){
867                                                             return function(){
868                                                              // alert(i)
869                                                              }
870                                                          }else if(i == (len-1)){
871                                                              var  o_input = id.getElementsByTagName(‘input‘)[0]; 
872                                                                        var vl ="";
873                                                                       o_input.onkeyup= function(){
874                                                                                this.value  =  trim(this.value);
875                                                                             if(this.value>=count){
876                                                                                       this.value = count;
877                                                                                 }
878                                                                                 if(this.value<=1){
879                                                                                        this.value = 1;
880                                                                                     }
881                                                                                      vl  = this.value;
882                                                                           }
883                                                             return function(){ 
884                                                                      /* if(page_arguments.motion){
885                                                                               if(control){return false;}
886                                                                        }*/
887                                                                         page_arguments.index =   parseInt(vl)||1;
888                                                                     //  page_arguments.control = control;
889                                                                       CQuery.setPage(page_arguments);
890                                                                       success({count:count, index:page_arguments.index});
891                                                              }
892                                                          }else{
893                                                            return function(){ 
894                                                                          /*if(page_arguments.motion){
895                                                                               if(control){return false;}
896                                                                        }*/
897                                                                          page_arguments.index =   parseInt(this.innerHTML);
898                                                                     //  page_arguments.control = control;
899                                                                       CQuery.setPage(page_arguments);
900                                                                       success({count:count, index:page_arguments.index});
901                                                                       return false;
902                                                                   }
903                                                          }
904                                        })(i);  
905                      }
906            }
907   CQuery.extend = function(obj){
908            for(i in obj){
909                  CQuery[i] =  obj[i];  
910               }
911       }
912       CQuery.inArray = function(arr_child,arr){
913            var in_array_index = -1;
914             forEach(arr,function(i){
915                      if(arr[i]==arr_child){
916                               in_array_index = i;
917                               return ;
918                          }
919                 });
920               (arguments.length==2)||(in_array_index=-1);
921               return   in_array_index;
922           }
923         CQuery.parseJSON = function(json_data){
924                return     JSON.parse(json_data);
925             } 
926          CQuery.isFunction =function(fn){
927                 if(checkType(data_type)==="[object Function]"){
928                       return true;
929                     }else{
930                           return false;
931                         }
932              }
933  
934 CQuery.isEmpty =  function(obj){
935              var is=false;
936              if(checkType(data_type)!=="[object Object]"){
937                    return is;
938                  }
939             for(i in obj){
940                     is=true; 
941                     if(is==1){
942                            break;
943                         }
944                 }
945      }
946     
947     CQuery.isPlainObject=function(obj){
948              if(checkType(data_type)==="[object Object]"){
949                    return true;
950                  }else{
951                        false;
952                      }
953         }
954     CQuery.isNumeric = function(num){
955               if(checkType(data_type)==="[object Nunber]"){
956                      return true;
957                  }else{
958                        false;
959                      }
960         }
961  
962  CQuery.type = function(data){
963        return typeof(data);
964      }    
965      CQuery.error= function( msg ) {
966                       throw new Error( msg );
967                    } 
968    window.fn = function(){};
969    window.$=window.jQuery = CQuery;
970    fn.prototype = CQuery.prototype;
971    fn.prototype.constructor = fn;
972    window.new_CQuery = new fn();
973  })(window,undefined,document);
974  

 

 

 

 

使用例子

<!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="cq.js"></script>
<style>
   div{
       width:100px;
       height:100px;
       background:red;
       position:absolute;
       left:100px;
       }
</style>
</head>
 <body>
 <script>
    $(function(){
            $(‘input‘).click(function(){
                     alert(1);
                });
            $(‘div‘).hover(function(){
                        console.log(0)
                },function(){
                            console.log(2)
                    }).click(function(){
                             $(this).animate({width:200,
                                                         height:200
                                                         },function(){
                                                                $(this).animate({
                                                                                           left:300
                                                                                         })
                                                             })
                        })
        });
 </script>
 <input type="button" value="按钮" />
 <div></div>
</body>
</html>

 

Cq 的ajax和jq的ajax差不多

最简单的json提交方式为

Var json = $.ajax({

                                         url:‘ajaxform1.php‘,  //必填

                                    data:‘username=爱上的方式地方‘,                                            

                                     })  

Alert(json)

 

最简单的文件上传为,这样与jq有些差别,大大减小了用户的传参

<input id=’fileId’  type=’file’ name = ‘file’>

$.ajax({

                                         url:‘ajaxform1.php‘,  //必填 

                                               success:function(data){

                                                           alert(data)

                                                        }

                                                dataType:’file’ ,

                     fileObject:$(‘# fileId’).get(0)

                                     })  

参数说明

url: 请求的url

fileObject: 文件对象 需要传文件的时候才需要设置这个

dataType:有两个参数 是选择json数据传输还是file文件上传 默认是json

success: ajax通信成功后回调函数

async: 同步或者异步 false为同步 true为异步 默认是true

type:  post提交或者是get提交  默认是post

cache: 提交的时候是否清理url缓存 默认是不清理 为true   清理为false

loading : 状态函数 ajax响应1234 状态函数 readyState

complete : ajax通信无论成功还是失败都调用该函数

error :ajax通信出错或者是服务器出错调用该函数

 

 

  1 <!doctype html>
  2 <html>
  3 <head>
  4 <meta charset="utf-8">
  5 <title>无标题文档</title>
  6 <script  src="../cq/cq.js">
  7     
  8 </script>
  9  <style>
 10      div{
 11           width:260px;
 12          height:90px;
 13          line-height:30px;
 14           text-align:left;
 15           border:3px #ccc dotted;
 16           padding:30px 30px 0px 30px;
 17           
 18           color:#666
 19           }
 20          
 21          .active{
 22              color:green;
 23               border-color:green;
 24            }
 25   </style>
 26 </head>
 27  <body>
 28     <div  id="box">
 29        一次性可以拖拽上传多个文件,请把需要上传文件的拖拉到此处
 30     </div>
 31     <form>
 32          
 33     </form>
 34     <script>
 35 /*
 36 ondrag             script 当拖动元素时运行脚本 
 37 ondragend       script 当拖动操作结束时运行脚本 
 38 ondragenter     script 当元素被拖动至有效的拖放目标时运行脚本  3
 39 ondragleave     script 当元素离开有效拖放目标时运行脚本 类似于out 
 40 ondragover      script 当元素被拖动至有效拖放目标上方时运行脚本 5
 41 ondragstart      script 当拖动操作开始时运行脚本 
 42 ondrop            script 当被拖动元素正在被拖放时运行脚本 
 43 
 44 阻止浏览器拖拽默认事件只需要清除这两个事件浏览器就不会自动打开文件了
 45 document.ondragover=document.ondrop=function(e){
 46                e.preventDefault();
 47                  return;} 
 48         经过测试拖拽文件的时候发生事件循序为
 49         ondragenter 只会触发一次事件,就是当文件拖拽到指定的元素的时候,如果不离开只会发生一次事件
 50         ondragover  如果元素拖拽到指定的位置的时候会一直不停的触发事件
 51         ondrop        只会触发一次事件是当文件拖拽到指定位置的时候并且放下去的时候,相当于mouseup事件
 52         ondragenter->ondragover->ondrop 
 53          ondragleave 只会触发一次事件当元素离开有效拖放目标时运行脚本 out
 54 */
 55 
 56 var box=document.getElementById("box");
 57   
 58      document.ondragenter=function(e){
 59           e.preventDefault();
 60               console.log(3);
 61                   
 62             } 
 63             
 64           document.ondrop=document.ondragover=function(e){
 65              e.preventDefault();
 66               console.log(5);
 67              // alert(2);
 68               return ;
 69             } 
 70             box.ondragover=function(e){
 71                    e.preventDefault();
 72               console.log(5);
 73             this.className=‘active‘;
 74             }
 75           box.ondrop=function(e){
 76              this.className=‘‘;
 77                 e.preventDefault();
 78                   console.log(7);
 79                 //e.dataTransfer文件的parent对象 文件对象还要点e.dataTransfer.files[0] 第一个文件对象
 80               console.log(e.dataTransfer);
 81               /*       ajax({
 82              method:‘post‘,    //默认是get方式可选
 83              url:‘06.php‘,  //必填
 84                type:"file", //如果是设置文件则是上传文件,不设置默认是发送数据  //可选
 85              //name:"file",//如果是设置了文件上传那么必须要填入表单设定的name
 86              Ofile:e.dataTransfer,  //如果是文件上传则(必填)需要穿一个文件对象过来,
 87              loading:function(readyState){/*alert(readyState) }, //可选
 88              success:function(dada){/*alert(dada); }  //服务器响应函数必填
 89                   });*/
 90                        $.ajax({
 91                     url:‘06.php‘,  //必填
 92                     fileObject:e.dataTransfer, 
 93                     dataType:‘file‘ 
 94                 })   
 95                  
 96                 return ;
 97             } 
 98          
 99               box.ondragleave =function(e){
100                  this.className=‘ ‘;
101                e.preventDefault();
102                console.log(4);
103               return ;
104             } 
105      </script>
106 </body>
107 </html>

 

一个类似于jq的小型库

标签:

原文地址:http://www.cnblogs.com/hao123456/p/5602210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!