10 most commonly used udfs in javascript [recommended]

Source: Internet
Author: User

(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: Copy codeThe Code is as follows: 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. Copy codeThe Code is as follows: // 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 for each event handler
If (! Handler. $ guid) handler. $ guid = addEvent. guid ++;
// Create a hash table for the event type of the element
If (! Element. events) element. events = {};
// Create a hash table for each "element/event" pair of event handlers
Var handlers = element. events [type];
If (! Handlers ){
Handlers = element. events [type] = {};
// Store existing event processing functions (if any)
If (element ["on" + type]) {
Handlers [0] = element ["on" + type];
}
}
// Store the event processing function into the hash table
Handlers [handler. $ guid] = handler;
// Assign a global event processing function to do all the work.
Element ["on" + type] = handleEvent;
};
// Create a counter with a unique ID
AddEvent. guid = 1;
Function removeEvent (element, type, handler ){
// Delete the event handler from the hash table
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 );
// Obtain the reference of the hash table of the event processing function
Var handlers = this. 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" functions to the IE event object
Function fixEvent (event ){
// Add standard W3C Method
Event. 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: Copy codeThe Code is as follows: 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:Copy codeThe Code 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:Copy codeCode: 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.Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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.Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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.Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: function setStyle (el, prop, value ){
If (prop = "opacity "&&! + "\ V1 "){
// IE7 bug: the filter must be hasLayout = true before it can be executed (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 (Ops =" + 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.Copy codeThe Code is as follows: 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.