Turn: 10 most commonly used udfs in Javascript

Source: Internet
Author: User

If you do not use a class library or do not have your own class library, it is always advantageous to reserve some common functions.

(10) addevent

The most popular version on the internet is Scott Andrew. It is said that the Javascript community held a competition (this event can be seen on Pro JavaScript techniques page 100th) or browsed the PPK website, ask for the function to add and remove events. He is the winner. The following is his implementation:

 
Function addevent (ELM, evtype, FN, usecapture) {If (Elm. addeventlistener) {Elm. addeventlistener (evtype, FN, usecapture); // dom2.0 return true;} else if (Elm. attachevent) {var r = Elm. attachevent ('on' + evtype, FN); // ie5 + return r;} else {elm ['on' + evtype] = FN; // Dom 0 }}

The following is the version of Dean Edwards.

// Addevent/removeevent written by Dean Edwards, 2005 // with input from Tino Zijdel/http://dean.edwards.name/weblog/2005/10/add-event/function addevent (element, type, Handler) {// assign a unique ID if (! Handler. $ guid) handler. $ guid = addevent. guid ++; // create a hash table if (! Element. Events) element. Events = {}; // process the creation of an event for each "element/event" Program VaR handlers = element. events [type]; If (! Handlers) {handlers = element. events [type] ={}; // stores existing event handler functions (if any) if (element ["on" + type]) {handlers [0] = element ["on" + type] ;}// Save the event handler to the hash table handlers [handler. $ guid] = handler; // assign a global event handler function for all work. Element ["on" + type] = handleevent ;}; // The counter addevent used to create a unique ID. guid = 1; function removeevent (element, type, Handler) {// Delete the event handler function if (element. events & element. events [type]) {Delete element. events [type] [handler. $ guid] ;}}; function handleevent (event) {var returnvalue = true; // capture event objects (ie uses global event objects) event = event | fixevent (window. event); // reference var handlers = this to obtain the hash table of the event processing function. events [event. type]; // execute each processing function for (var I in handlers) {This. $ handleevent = handlers [I]; If (this. $ handleevent (event) === false) {returnvalue = false ;}} return returnvalue ;}; // Add some "missing" function fixevent (event) {// Add standard W3C method event for the IE event object. preventdefault = fixevent. preventdefault; event. stoppropagation = fixevent. stoppropagation; return event;}; fixevent. preventdefault = function () {This. returnvalue = false ;}; fixevent. stoppropagation = function () {This. cancelbubble = true ;};

This feature is very powerful, solving this point problem of IE. event is always passed as the first parameter, so cross-browser communication is even more difficult.

In addition, I have also collected an HTML5 workgroup version:

 
VaR addevent = (function () {If (document. addeventlistener) {return function (El, type, FN) {If (El. length) {for (VAR I = 0; I <el. length; I ++) {addevent (El [I], type, FN) ;}} else {el. addeventlistener (type, FN, false) ;};} else {return function (El, type, FN) {If (El. length) {for (VAR I = 0; I <el. length; I ++) {addevent (El [I], type, FN) ;}} else {el. attachevent ('on' + type, function () {return fn. call (El, window. event );});}};}})();

(9) addloadevent ()

I have discussed this function before. In other words, it is a little slower. All major libraries basically ignore it and implement the domready version on their own. The implementation of Simon willison is as follows:

VaR addloadevent = function (FN) {var oldonload = Window. onload; If (typeof window. onload! = 'Function') {window. onload = FN;} else {window. onload = function () {oldonload (); FN ();}}}

(8) getelementsbyclass ()

I have a collection addiction, I have a lot of versions on hand, and finally I made it by myself. The following is my implementation:

VaR getelementsbyclassname = function (searchclass, node, tag) {If (document. getelementsbyclassname) {return document. getelementsbyclassname (searchclass)} else {node = node | document; tag = tag | "*"; var classes = searchclass. split (""), elements = (TAG = "*" & node. all )? Node. ALL: node. getelementsbytagname (TAG), patterns = [], returnelements = [], current, match; var I = classes. length; while (-- I> = 0) {patterns. push (New Regexp ("(^ | \ s)" + classes [I] + "(\ s | $)");} var J = elements. length; while (-- j> = 0) {current = elements [J]; match = false; For (var k = 0, KL = patterns. length; k <kl; k ++) {match = patterns [K]. test (current. classname); If (! Match) break;} If (MATCH) returnelements. Push (current);} return returnelements ;}}

(7) cssquery ()

The alias is getelementsbyseletor, which is first implemented by Dean Edwards. class libraries such as prototype. js and jquery are all implemented accordingly. Among them, jquery integrates it into the $ () selector, which is famous for its predecessors. However, IE8 and Other cutting-edge browsers have implemented the queryselector and queryselectorall methods. When IE6 and IE7 are decommissioned, it will be useless. There is no worries about its implementation principles. Because it is too long, it will not be stuck. For details, visit the original author's website.

(6) Toggle ()

Used to show or hide a DOM element.

 
Function toggle (OBJ) {var El = Document. getelementbyid (OBJ); If (El. style. display! = 'None') {El. style. Display = 'none';} else {El. style. Display = '';}}

(5) insertafter ()

Dom only provides insertbefore, and we need to implement insertafter on our own. However, I think insertadjacentelement is a better choice. Now, all the browsers except Firefox implement this method. The following is the version of Jeremy KEITH:

 
Function insertafter (parent, node, referencenode) {parent. insertbefore (node, referencenode. nextsibling );}

(4) inarray ()

Used to check whether a value exists in the array. The following method is taken from the prototype class library.

Array. prototype. inarray = function (value) {for (VAR I = 0, L = This. length; I <L; I ++) {If (this [I] === value) {return true ;}} return false ;};

Another version:

 
VaR inarray = function (ARR, value) {for (VAR I = 0, L = arr. length; I <L; I ++) {If (ARR [I] === value) {return true ;}} return false ;};

(3) getcookie (), setcookie (), deletecookie ()

BBS and commercial websites should be used frequently. There is no reason to ask the user to enter a password to log on each time. We need to use cookies for automatic login.

Function getcookie (name) {var start = Document. Cookie. indexof (name + "="); var Len = start + name. Length + 1; if ((! Start) & (name! = Document. cookie. substring (0, name. length) {return NULL;} If (START =-1) return NULL; var end = document. cookie. indexof (';', Len); If (END =-1) End = document. cookie. length; return Unescape (document. cookie. substring (Len, end);} function setcookie (name, value, expires, path, domain, secure) {var today = new date (); today. settime (today. gettime (); If (expires) {expires = expires * 1000*60*60*24;} var expires_date = new date (today. gettime () + (expires); document. cookie = Name + '=' + escape (value) + (expires )? '; Expires =' + expires_date.togmtstring (): '') + // expires. togmtstring () (PATH )? '; Path =' + path: '') + (domain )? '; Domain =' + domain: '') + (secure )? '; Secure': '');} function deletecookie (name, path, domain) {If (getcookie (name) document. cookie = Name + '=' + (PATH )? '; Path =' + path: '') + (domain )? '; Domain =' + domain: '') + '; expires = Thu, 01-Jan-1970 00:00:01 gmt ';}

(2) getstyle () and setstyle ()

All UI controls should have functions that dynamically set styles and obtain styles. This can be written very short or very long, but it must be accurate to get the style, a word: difficult! However, I found that many problems originated from IE. Microsoft developers never seem to want to provide functions such as getcomputedstyle. The similar currentstyle will return auto, inhert, ''. It makes you laugh and cry. This is not counted as the difficulty of the IE strange pattern! The implementation of various libraries is very long and difficult to separate. The following is my implementation version:

Function setstyle (El, prop, value) {If (prop = "opacity "&&! + "\ V1") {// IE7 BUG: the filter must be haslayout = true (otherwise it will not work) if (! El. currentstyle |! El. currentstyle. haslayout) El. style. Zoom = 1; prop = "filter"; if (!! Window. xdomainrequest) {value = "progid: DXImageTransform. microsoft. alpha (style = 0, opacity = "+ value * 100 +") ";} else {value =" alpha (opacity = "+ value * 100 + ") "}} el.style.css text + = ';' + (prop +": "+ value);} function getstyle (El, style) {If (! + "\ V1") {style = style. replace (/\-(\ W)/g, function (all, letter) {return letter. touppercase () ;}); return el. currentstyle [style];} else {return document. defaultview. getcomputedstyle (El, null ). getpropertyvalue (style )}}

For setstyle, you can also read another blog post. After all, the styles set now are inline styles mixed with HTML.

(1) $ ()

Actually, the most valuable function can save a lot of traffic. It was first implemented by prototype. js. It is a rare animal left behind by the flood of times, and now there are many variants.

 
Function $ () {var elements = []; for (VAR I = 0; I <arguments. length; I ++) {var element = arguments [I]; If (typeof element = 'string') element = document. getelementbyid (element); If (arguments. length = 1) return element; elements. push (element);} return elements ;}
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.