(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:
CopyCode The 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 code The 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 an event for each "element/event" Program Hash table
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;
};
the function 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 Working Group version: copy Code the code is as follows: var addevent = (function () {
If (document. addeventlistener) {
return function (El, type, FN) {
If (El. length) {
for (VAR I = 0; I addevent (El [I], type, FN);
}< BR >}else {
el. addeventlistener (type, FN, false);
}< BR >};
}else {
return function (El, type, FN) {
If (El. length) {
for (VAR I = 0; I addevent (El [I], type, FN);
}< BR >}else {
el. attachevent ('on' + type, function () {
return fn. call (El, window. event);
});
}< BR >};
}< BR >}) ();
(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 code Code: 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 code The 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 code The 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;
}