JavaScript 10 most commonly used custom functions (Chinese version) _javascript tips

Source: Internet
Author: User
Tags hash setcookie unique id
(a) Addevent
The most popular version on the web is Scott Andrew, who is said to have played a game in the JavaScript world (which we can see on page 100th of Pro JavaScript techniques) or browse the PPK Web site to solicit the functions for adding events and removing events. He is the winner. The following is his implementation:
Copy Code code 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
}
}

Here's the version of Dean Edwards.
Copy Code code as follows:

Addevent/removeevent written by Dean Edwards, 2005
With the input from Tino Zijdel
http://dean.edwards.name/weblog/2005/10/add-event/
function addevent (element, type, handler) {
Assign a unique ID to each event handler function
if (!handler.$ $guid) handler.$ $guid = addevent.guid++;
Create a hash table for the element's event type
if (!element.events) element.events = {};
Create an event handler for each "element/event" hash table
var handlers = Element.events[type];
if (!handlers) {
Handlers = Element.events[type] = {};
Store existing event handler functions (if any)
if (element["on" + type]) {
Handlers[0] = element["on" + type];
}
}
To save an event handler function in a hash table
handlers[handler.$ $guid] = handler;
Assign a global event handler function to do all the work
Element["on" + type] = Handleevent;
};
A counter used to create a unique ID
Addevent.guid = 1;
function removeevent (element, type, handler) {
To remove an 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 object (ie uses global event object)
Event = Event | | Fixevent (window.event);
Gets a reference to the hash table of the event handler function
var handlers = This.events[event.type];
Perform each handler function
for (var i in handlers) {
this.$ $handleEvent = handlers[i];
if (this.$ $handleEvent (event) = = False) {
ReturnValue = false;
}
}
Return returnvalue;
};
Add some "missing" functions for IE's Event object
function Fixevent (event) {
To add a standard method of the Consortium
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 formidable, solves the IE the this to point to the question, the event always as the first parameter passes in, the cross browser is not to mention.
In addition, I have also treasured a version of the HTML5 workgroup:
Copy Code code 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, not in detail, is a bit slow, the major class libraries basically ignore it, the implementation of the Domready version. Here is the implementation of Simon Willison:
Copy Code code 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 fetish, with many versions on hand, and finally brainstorming myself to achieve one. Here is my implementation:
Copy Code code as follows:

var getelementsbyclassname = function (Searchclass, node,tag) {
if (docum Ent.getelementsbyclassname) {
return document.getelementsbyclassname (searchclass)
}else{
node = node | | d ocument;
Tag = Tag | | "*";
var classes = Searchclass.split (""),
elements = (Tag = = "*" && node.all)? Node.all:node.getElementsByTagName (tag),
patterns = [],
returnelements = [],
Current,
match;
var i = classes.length;
while (>= 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 ()
Alias for Getelementsbyseletor, the first implementation by Dean Edwards, Prototype.js,jquery and other class libraries have a corresponding implementation, where jquery integrates it into the $ () selector, reputation over its predecessors. However, IE8, such as the new browser has been implemented Queryselector and Queryselectorall method, until IE6 and IE7 scrapped the day, it is useless. There is no worry in the realization of its principle to explain. Because too long, will not stick out, specific to the original author website to see.
(6) Toggle ()
Used to show or hide a DOM element.
Copy Code code 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 provides only insertbefore, and it is necessary for us to implement insertafter ourselves. But I think insertadjacentelement is a better choice, and now it is implemented in addition to other Firefox browsers. Here's the Jeremy Keith version:
Copy Code code as follows:

function InsertAfter (Parent, node, Referencenode) {
Parent.insertbefore (node, referencenode.nextsibling);
}

(4) InArray ()
Used to determine if a value exists in the check array, the following method is taken from the prototype class library.
Copy Code code 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 Code code 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 ()
Do BBS and commercial website should often use, there is no reason to let users enter the password every time to log in. We need to use cookies to implement the automatic login function.
Copy Code code 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)? ';p ath= ' + path: ') +
(domain)? ';d omain= ' + domain: ') +
(secure)? '; secure ': ';
}
function Deletecookie (name, path, domain) {
if (GetCookie (name)) Document.cookie = name + ' = ' +
((path)? ';p ath= ' + path: ') +
(domain)? ';d omain= ' + domain: ') +
'; Expires=thu, 01-jan-1970 00:00:01 GMT ';
}

(2) GetStyle () and SetStyle ()
Functions that all UI controls should exist to dynamically set styles and get styles. This can be written very short, but also can be written very long, but to get the exact style, a word: difficult! But I found that a lot of problems are originated in IE, Microsoft's developers seem to have never intended to give getcomputedstyle such a function, and the similar currentstyle will return to Auto,inhert, "and so let you laugh and cry the value, This is not yet counted on the difficulty of IE quirks mode! The implementation of all kinds of libraries is very long and difficult to separate out, the following is my implementation of the version:
Copy Code code as follows:

function SetStyle (el,prop,value) {
if (prop = = "opacity" &&!+ "\v1") {
IE7 bug:filter filter requires Haslayout=true to execute (otherwise no effect)
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.cssText + = '; ' + (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)
}
}

About SetStyle can also see me another blog, after all, now set the style is inline style, and HTML mixed together.
(1) $ ()
Well deserved, the most valuable function, can save how much traffic ah. The first to be realized by Prototype.js, which is the legacy of the prehistoric time, there are many varieties of the precious beast.
Copy Code code 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.