4 common functions of native javascript are recommended
This article mainly introduces the recommendation of four common native javascript Functions. For more information, see
[1] add listener events
The Code is as follows:
AddHandler: function (node, type, fn) {if (node. addEventListener ){
Node. addEventListener (type, fn, false); // false, set as a bubble event
}
Else {
Node. attachEvent ('on' + type, function (){
Fn. apply (node, arguments); // In the attachEvent method, this does not point to node, so you need to change it using the apply () method.
});
}
}
[2] set the element style
The Code is as follows:
SetCss: function (node, val) {// val: {'top': '2px ', 'font-size': '12px '}
For (var v in val ){
Node.style.css Text + = ';' + v + ':' + val [v]; // you can use cssText to set multiple attributes at the same time. Another benefit is to avoid cssFloat, determination of styleFloat
}
}
[3] retrieving CSS class name elements
The Code is as follows:
// Parent is an optional parameter,
GetByClassName: function (className, parent ){
Var elem = [],
Node = parent! = Undefined & parent. nodeType = 1? Parent. getElementsByTagName ('*'): document. getElementsByTagName ('*'),
P = new RegExp ("(^ | \ s)" + className + "(\ s | $ )");
For (var n = 0, I = node. length; n <I; n ++ ){
If (p. test (node [n]. className )){
Elem. push (node [n]);
}
}
Return elem;
}
Iv. Delete the CSS Class Name
The Code is as follows:
RemoveClassName: function (node, className ){
Var par = new RegExp (className, 'G ');
Node. className = node. className. replace (par ,'');
}
The above four are native js functions that are very practical and frequently used. We recommend them to our friends and hope to help you.