


The ten most commonly used custom functions in javascript (Chinese version)_javascript skills
(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:
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
// 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:
var addEvent=(function(){
if(document.addEventListener){
return function(el,type,fn){
if(el.length){
for( var i=0;i
}
}else{
el.addEventListener(type,fn, false);
}
};
}else{
return function(el,type,fn){
if(el.length){
for(var i=0 ;i
}
}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:
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:
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
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.
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:
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.
Array.prototype.inArray = function (value) {
for (var i=0,l = this.length ; i
return true;
}
}
return false;
};
Another version:
var inArray = function (arr,value) {
for (var i=0,l = arr.length ; i
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.
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;
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use Python to write custom functions in MySQL MySQL is an open source relational database management system that is often used to store and manage large amounts of data. As a powerful programming language, Python can be seamlessly integrated with MySQL. In MySQL, we often need to use custom functions to complete some specific calculations or data processing operations. This article will introduce how to use Python to write custom functions and integrate them into MySQL. For writing custom functions,

A function is a set of reusable code blocks that perform a specific task (have a specific functionality). In addition to using built-in functions, we can also create our own functions (custom functions) and then call this function where needed. This not only avoids writing repeated code, but also facilitates the later maintenance of the code.

Basic knowledge of functions: Master the basic syntax specifications and calling methods of custom functions, and master the usage and calling rules of various parameters of functions. 1. Python function (Function) is an organized, reusable code segment used to implement a single or related function. Functions can improve application modularity and code reuse. We have already touched on many of the built-in functions provided by Python, such as print(). But you can also create your own functions, which are called user-defined functions. 2. Basic rules for customizing a function. You can define a function with the functions you want. The following are simple rules: the function code block starts with the def keyword, followed by the function identifier name and parentheses.

In PHP, a function is a set of reusable blocks of code that are identified by a name. PHP supports a large number of ready-made functions, such as array_push, explode, etc., but sometimes you need to write your own functions to implement specific functions or improve code reusability. In this article, I will introduce how to customize functions in PHP, including function declaration, calling and using function parameters. Declaration of functions To declare a function in PHP, you need to use the keyword function. The basic syntax of the function is as follows:

How to write custom stored procedures and functions in MySQL using PHP In the MySQL database, stored procedures and functions are powerful tools that allow us to create custom logic and functions in the database. They can be used to perform complex calculations, data processing and business logic. This article will introduce how to write custom stored procedures and functions using PHP, with specific code examples. Connecting to the MySQL database First, we need to connect to the MySQL database using the MySQL extension for PHP. can use

PHP custom functions allow encapsulating code blocks, simplifying code and improving maintainability. Syntax: functionfunction_name(argument1,argument2,...){//code block}. Create function: functioncalculate_area($length,$width){return$length*$width;}. Call the function: $area=calculate_area(5,10);. Practical case: Use a custom function to calculate the total price of the items in the shopping cart, simplifying the code and improving readability.

Golang is a very popular programming language with a very powerful function library. In Golang, functions are considered first-class citizens, which means that Golang functions can be passed, copied, and overloaded like variables. In addition, Golang also provides two types of built-in functions and custom functions. In this article, we will explore the pros and cons of built-in functions and custom functions in Golang to help readers understand when to choose which type of function. First, let's look at the built-in functions. built-in letter

Function parameters are the bridge between the inside of the function and the outside of the function. The following article will take you through the parameters in JavaScript functions. I hope it will be helpful to you!
