Home  >  Article  >  Web Front-end  >  The ten most commonly used custom functions in javascript (Chinese version)_javascript skills

The ten most commonly used custom functions in javascript (Chinese version)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:47:14960browse

(10)addEvent
The most popular version on the Internet is Scott Andrew's. It is said that the JavaScript community once held a competition (we can see this event on page 100 of Pro Javascript Techniques) or browse the PPK website to solicit additions of events and The function that removes the event, he is its winner. The following is his implementation:

Copy code 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 Dean Edwards’ version
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 to each event handler function
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 of event handlers for each "element/event" pair
var handlers = element.events[type];
if (!handlers) {
handlers = element .events[type] = {};
//Storage existing event handlers (if any)
if (element["on" type]) {
handlers[0] = element["on " type];
}
}
//Save the event handler function into the hash table
handlers[handler.$$guid] = handler;
//Assign a global event The handler function does all the work
element["on" type] = handleEvent;
};
//Counter used to create unique IDs
addEvent.guid = 1;
function removeEvent(element, type, handler) {
//Delete event handler function from hash table
if (element.events && element.events[type]) {
delete element.events[type ][handler.$$guid];
}
};
function handleEvent(event) {
var returnValue = true;
//Capture the event object (IE uses the global event object)
event = event || fixEvent(window.event);
//Get a reference to the hash table of the event handling function
var handlers = this.events[event.type];
// Execute 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 to IE's 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 and solves the this pointing problem of IE. Event is always passed in as the first parameter, making cross-browser easy.
In addition, I also treasured a version of the HTML5 working group:
Copy the code The code is as follows:

var addEvent=(function(){
if(document.addEventListener){
return function(el,type,fn){
if(el.length){
for( var i=0;iaddEvent(el[i],type,fn);
}
}else{
el.addEventListener(type,fn, false);
}
};
}else{
return function(el,type,fn){
if(el.length){
for(var i=0 ;iaddEvent(el[i],type,fn);
}
}else{
el.attachEvent('on' type,function() {
return fn.call(el,window.event);
});
}
};
}
})();

(9) addLoadEvent()
I have discussed this function before. Without going into details, it is just a little slow. Major libraries basically ignore it and implement the domReady version by themselves. The following is Simon Willison's implementation:
Copy code The 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 collecting habit and have many versions on hand, and finally I brainstormed and implemented one myself. The following is my implementation:
Copy code The code is as follows:

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; kmatch = patterns[k].test(current.className);
if (!match) break;
}
if (match) returnElements.push(current);
}
return returnElements;
}
}

(7) cssQuery()
The alias is getElementsBySeletor, which was first implemented by Dean Edwards. Prototype.js, JQuery and other class libraries are There is a corresponding implementation, among which JQuery integrates it into the $() selector, and its reputation exceeds that of its predecessors. However, cutting-edge browsers such as IE8 have already implemented the querySelector and querySelectorAll methods. When IE6 and IE7 are scrapped, they will be useless. Wuyou has an explanation of its implementation principles. Because it's too long, it won't stick out. You can check the original author's website for details.
(6) toggle()
is used to show or hide a DOM element.
Copy code The 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, it is necessary for us to implement insertAfter ourselves. But I think insertAdjacentElement is a better choice. Now all browsers except Firefox implement this method. Here is Jeremy Keith’s version:
Copy code The code is as follows:

function insertAfter(parent, node, referenceNode) {
parent.insertBefore(node, referenceNode.nextSibling);
}

(4) inArray()
is used to determine whether something exists in the check array value, the following methods are taken from the Prototype class library.
Copy code The code is as follows:

Array.prototype.inArray = function (value) {
for (var i=0,l = this.length ; i if (this[i] === value) {
return true;
}
}
return false;
};

Another version:
Copy code The code is as follows:

var inArray = function (arr,value) {
for (var i=0,l = arr.length ; i if (arr[i] === value) {
return true;
}
}
return false;
};

(3) getCookie(), setCookie(), deleteCookie()
Those who make BBS and commercial websites should use it frequently. There is no reason to ask users to enter a password to log in every time. We need to use cookies to implement the automatic login function.
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()与setStyle()
所有UI控件都应该存在的函数,动态设置样式与获取样式。这个可以写得很短,也可以写得很长,但要精确取得样式,一个字:难!但我发现许多问题都是发端于IE,微软的开发人员好像从来不打算给出getComputedStyle这样的函数,与之相近的currentStyle会返回auto,inhert, ' '等让你哭笑不得的值,这还没有算上IE怪癖模式带来的难度呢!各类库的实现是非常长与难分离出来的,下面是我实现的版本:
复制代码 代码如下:

function setStyle(el,prop,value){
if(prop == "opacity" && ! "v1"){
//IE7 bug:filter 滤镜要求 hasLayout=true 方可执行(否则没有效果)
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)
}
}

有关setStyle还可以看我另一篇博文,毕竟现在设置的样式都是内联样式,与html混杂在一起。
(1)$()
实至名归,最值钱的函数,可以节省多少流量啊。最先由Prototype.js实现的,那是洪荒时代遗留下来的珍兽,现在有许多变种。
复制代码 代码如下:

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;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn