search
HomeWeb Front-endJS Tutorialjavascript 10 most commonly used custom functions [recommended]_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 PPK's The website asked for functions to add events and remove events, and he was the 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) {
//Dispatch a unique event handler for each event ID
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 handler to do all the work
element["on" type] = handleEvent;
};
//Counter used to create unique IDs
addEvent.guid = 1;
function removeEvent(element, type, handler) {
//Remove 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 global event objects)
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 IE's this pointing problem. event is always passed in as the first parameter, and cross-browser is no problem.
In addition, I also treasured a version of the HTML5 working group:
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;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 domReady by themselves. Version. 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, first implemented by Dean Edwards, Prototype.js , JQuery and other class libraries have corresponding implementations. Among them, JQuery integrated 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, which is necessary for us Implement insertAfter yourself. 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 for judgment Check whether a certain value exists in the array. The following method is 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()
It should be used frequently by BBS and commercial websites. There is no reason to ask users to enter their 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 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software