JQuery learning path (7)-using native JavaScript to implement some simple functions of jQuery, javascriptjquery

Source: Internet
Author: User

JQuery learning path (7)-using native JavaScript to implement some simple functions of jQuery, javascriptjquery
Too many rows too many rowsIntroduction

I learned how to use native JavaScript to implement some functions of jQuery.

Define your own function library lQuery

 

▓ $ () Selector implementation

JQuery is object-oriented, so I write it myself as well. Let's look at the basic structure.

1 // define the lQuery object 2 function lQuery (lArg) {3 4 5} 6 7 function SCSI (lArg) {8 return new lQuery (lArg ); 9 10} 11 12 // css () method 13 lQuery.prototype.css = function () {}; 14 15 // html () method 16 lQuery.prototype.html = function (){};

 

    First, let's copy the $ (function) method in jQuery.

1 // define lQuery object 2 function lQuery (lArg) {3 4 // use typeof to determine whether the parameter type is function, 5 switch (typeof lArg) {6 case 'function ': 7 // if this method is used, the same function is bound to the SCSI, but only 8 // window is executed once. onload = lArg; 9 // break; 10} 11 12}

If such a function is written, a problem may occur.

 1         lQ(function(){ 2  3             alert(1); 4  5         }); 6         lQ(function(){ 7  8             alert(2); 9 10         });

In this way, only '2' is displayed, but it is displayed in jQuery. Therefore, the above method is incorrect. We use event binding to solve this problem.

1 // bind event function 2 function lQbind (obj, eventName, fn) {3 // standard browser 4 if (obj. addEventListener) {5 obj. addEventListener (eventName, fn, false); 6} else {7 // IE browser 8 obj. attachEvent ('on' + eventName, fn); 9} 10}

You can use this method to call

1 switch (typeof lArg) {2 case 'function': 3 // if this method is used, bind the same function to the SCSI, but only execute 4 // window. onload = lArg; 5 // break; 6 lQbind (window, 'load', lArg); 7 break; 8}

 

    The $ ('. div'), $ ('# div'), and $ ('div ') methods in jQuery are imitated.

The difference between the three methods is that the first character is different, so we can treat the difference according to the first character.

First, copy $ ('. div ')

1                     // '.div'2                 case '.':3                     this.elements = getClass(document,lArg.substring(1));4                     break;

 

Because getElementsByClassName () is a method in HTML5, it is incompatible with IE8 or earlier, so we write a simple getClass method.

1 // obtain the class attribute 2 function getClass (obj, name) {3 var arr = []; 4 var elems = obj. getElementsByTagName ('*'); 5 for (var I = 0; I <elems. length; I ++) {6 if (elems [I]. className = name) {7 arr. push (elems [I]); 8} 9} 10 return arr; 11}

 

Copywriting $ ('# div ')

1                 case '#':2                     this.elements.push(document.getElementById(lArg.substring(1)));3                     break;4                     // '.div'5                 case '.':

 

Copywriting $ ('div ')

1 default: 2 // getElementsByTagName returns a class array NodeList. To prevent future troubles, convert it into a 3 // Array 4 this. elements = toArray (document. getElementsByTagName (lArg); 5 break;

Because getElementsByTagName returns a class array NodeList, to prevent future troubles, convert it into an array and customize a toArray method.

1 // convert an array of classes to a real array. 2 function toArray (lickArr) {3 var arr = []; 4 for (var I = 0; I <lickArr. length; I ++) {5 arr. push (lickArr [I]); 6} 7 return arr; 8}

 

 $ (Object) Method

1         // window  document2         case 'object':3             this.elements.push(lArg);4             break;
Implementation of ▓ html ()

The html () method consists of parameters and parameters.

1 // html () method 2 lQuery.prototype.html = function (str) {3 4 if (str) {// set 5 for (var I = 0; I <this. elements. length; I ++) {6 this. elements [I]. innerHTML = str; 7} 8} else {9 return this. elements [0]. innerHTML; 10} 11 return this; 12 13 };

 

Implementation of the zookeeper regression on () method

The previously implemented binding function can be easily implemented.

1 lQuery.prototype.on = function(eventName,fn){2     for(var i=0;i<this.elements.length;i++){3         lQbind(this.elements[i],eventName,fn);4     }5 }

 

Implementation of the two methods: click () and mouseover ()

The on () method can be easily implemented.

1 // click () method 2 lQuery. prototype. click = function (fn) {3 this. on ('click', fn); 4 return this; 5} 6 7 // mouseover () method 8 lQuery. prototype. mouseover = function (fn) {9 this. on ('mouseover', fn); 10 return this; 11}

 

Implementation of the two show () and show () Methods
1 // hide () method 2 lQuery. prototype. hide = function () {3 4 for (var I = 0; I <this. elements. length; I ++) {5 this. elements [I]. style. display = 'none'; 6} 7 return this; 8} 9 10 // show () method 11 lQuery. prototype. show = function () {12 13 for (var I = 0; I <this. elements. length; I ++) {14 this. elements [I]. style. display = 'block'; 15} 16 return this; 17}

 

 

Implementation of the zookeeper distributed handler hover () method
1 // hover () method 2 lQuery. prototype. hover = function (fnover, fnout) {3 this. on ('mouseover', fnover); 4 this. on ('mouseout', fnout); 5 return this; 6}

 

Implementation of the ▓ css () method

Actually ('div'0000.css('width'limit and limit ('div'0000.css ('width', '200px ')

 1 lQuery.prototype.css = function(attr,value){ 2     if(arguments.length == 2){ 3         for(var i=0;i<this.elements.length;i++){ 4             this.elements[i].attr = value; 5         } 6     } 7  8     if(arguments.length == 1){ 9         return getStyle(this.elements[0],attr);10     }11 }

The getStyle () method is defined to find a style other than the style in the row.

1 // obtain the property 2 function getStyle (obj, attr) {3 if (obj. currentStyle [attr]) {4 obj. currentStyle [attr]; 5} else {6 obj. getComputedStyle (obj, false) [attr]; 7} 8}

 

Implementation of the ▓ attr () method

Different methods are used from css ().

1 // attr () method 2 lquery. prototype. attr = function (attr, value) {3 4 if (arguments. length = 2) {// set 5 for (var I = 0; I <this. elements. length; I ++) {6 this. elements [I]. setAttribute (attr, value); 7} 8} 9 else if (arguments. length = 1) {// get 10 return this. elements [0]. getAttribute (attr); 11} 12 return this; 13 };

 

Implementation of ▓ eq () method

Implement $ ('div '). eq (1)

Because the objects returned by the eq () method need to operate many lQuery methods, the returned objects must be lQuery objects.

1         lQuery.prototype.eq = function(num){2             return lQ(this.elements[num]);3         };

 

▓ Index () method implementation

Implement $ ('div '). index () to return the position of this element in the Peer Element

 1         lQuery.prototype.index = function(){ 2          3         var elems = this.elements[0].parentNode.children; 4          5         for(var i=0;i<elems.length;i++){ 6             if( elems[i] == this.elements[0] ){ 7                 return i; 8             } 9         }10     };    

 

Too many events prevent default events and prevent event bubbles

In jQuery, return false is used to prevent default events and event bubbles. Therefore, we need to modify the lQbind function, determine whether to block default events and prevent event bubbles by checking whether the returned value of the bound function is false.

 1     function lQbind(obj,events,fn){ 2             if(obj.addEventListener){ 3                 obj.addEventListener(events,function(ev){ 4                      5                     if( fn() == false ){ 6                         ev.preventDefault(); 7                         ev.cancelBubble = true; 8                     } 9                     10                 },false);11             }12             else{13                 obj.attachEvent('on'+events,function(){14                     15                     if( fn() == false ){16                         window.event.cancelBubble = true;17                         return false;18                     }19                     20                 });21             }22         }

 

▓ Find () method implementation

$ ('Div '). find ('. box') and $ ('div '). find (' # box') Methods

Here we need to determine the method of determining the first character of the find () parameter to perform different operations, which is similar to the $ () method. In the loop, we need to use the concat () method to connect to the array, returns an lQuery object.

 1         lQuery.prototype.find = function(sel){ 2              3             var arr = []; 4              5             if( sel.charAt(0) == '.' ){  6                 for(var i=0;i<this.elements.length;i++){     7                     arr = arr.concat(getClass( this.elements[i] , sel.substring(1) )); 8                 } 9             }10             else{  11                 for(var i=0;i<this.elements.length;i++){    12                     arr = arr.concat(toArray(this.elements[i].getElementsByTagName(sel)));13                 }14             }15             return lQ(arr);    16         };

 

    

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.