Starting from the foundation to build a JS code base 1th/2 page _javascript tips

Source: Internet
Author: User
Tags anonymous arrays html tags
Because the background program filters out single quotes, there are some places where Maumin strange spaces are represented by single quotes.
/**
* @author Super Sha
* qq:770104121
* email:supersha@foxmail.com
* All Rights reserved!
*/
(function () {//original
function $ (s) {
if (!s)
return false;
return s.constructor = = String? document.getElementById (s): s;
}
window.$ = $;
})();

(function () {//anonymous encapsulate functions and execute, functions defined within this function or variable can be universal, the function can not be accessed outside, unless you declare under the namespace
if (!window. SUSA)
window[Susa] = {}; Declaring Susa namespaces
/*
* Get references to elements
*/
function $ () {
var elems = new Array ();
for (var i = 0; i < arguments.length; i++) {
var elem = arguments[i];
if (typeof arguments[i] = = "string") {//type checking
Elem = document.getElementById (Arguments[i]);
}
This has the meaning of pun: If a string is passed in and there is only one argument, or the DOM reference is passed in, the DOM node reference is returned
if (arguments.length = = 1) {
return elem;
}
else {
Elems.push (Elem);
}
}
return elems;
}
window[Susa] [$] = $;

/*
* Returns a child element within a specific element, or document
*/
function tag (type, elem) {
Elem = Elem | | Document
Type = Type | | "*"; If there are no parameters, a reference to all elements of the document is returned
return Elem.getelementsbytagname (type);
}
window[Susa [tag] = tag;

/*
* Returns the value of the input box
*/
function value (ID) {
var Elem = $ (ID); Calling methods defined within an anonymous function
if (Elem!= null && (Elem.nodename = = INPUT | | | elem.nodename = = TEXTAREA)) {
return elem.value;
}
}
window[Susa] [value] = value;

/*
* StringBuilder object//(original) that can quickly connect strings
*/
var StringBuilder = {
_arr:new Array,
Append:function (str) {
if (typeof str = = "string") {
This._arr.push (str);
}
return this;
},
Tostring:function () {
if (this._arr.length!= 0) {
var STRs = This._arr.join (,);
This._arr = []; Troubleshooting tips for returning duplicate additions
return STRs;
}
else {
return null;
}
}
}
function appendstring () {
for (Var i=0;i<3;i++) {
Stringbuilder.append ("test");
// }
return stringbuilder.tostring ();
//}
window[Susa] [str]=appendstring;

/*
* Addevent and Romoveevent methods
*/
function addevent (elem, type, fn) {
if (Elem!= $ (elem) | | | elem = = NULL)
return false;
if (type = NULL | | fn = NULL)
return false;

Method of if (Elem.addeventlistener) {//W3C
Elem.addeventlistener (Type, FN, false);
return true;
}
Else
if (elem.attachevent) {//IE method
node[e +type+fn]=fn;
Node[type+fn]=function () {
node[e +type+fn] (window.event); I don't know why I'm doing this.
//}
Node.attachevent (on +TYPE,NODE[TYPE+FN]);
return this;
Elem.attachevent (on + type, function () {
Fn.call (Elem)
});
Note: An anonymous function is used here to prevent the this object from pointing incorrectly in IE
return this;
}
else {
Elem["on" + type] = function () {
Fn.call (Elem)
};
}
}
function removeevent (elem, type, fn) {
if (Elem!= $ (elem) | | | elem = = NULL)
return false;
if (type = NULL | | fn = NULL)
return false;

Method of if (Elem.removeeventlistener) {//W3C
Elem.removeeventlistener (Type, FN, false);
return true;
}
Else
if (elem.detachevent)//IE method
{
Node.detachevent (on +TYPE,NODE[TYPE+FN]);
Elem.detachevent (on + type, fn);
return this;
}
}
window[Susa] [addevent] = addevent;
window[Susa] [removeevent] = removeevent;

/*
* The Getelementsbyclassname method returns a reference to all elements of a particular class, and the tag and elem parameters are optional
*/
function Getelementsbyclassname (classname, tag, elem) {
Elem = Elem | | Document
if (Elem!= $ (elem) | | | elem = = NULL)
return false;
Notice the Parent.all usage of this function, which is used to confirm whether the parent is document, and to distinguish between IE and mozilia
if (!tag)
Tag = "*";
var alltags = (Tag = = * && elem.all)? Elem.all:elem.getElementsByTagName (tag);

Creates a regular that detects whether the specified class name is included
classname = Classname.replace (/\-/g, "\\-");
var regex = new RegExp ("(^|\\s*)" + classname + "(\\s*|$)");

var matchelements = new Array ();
var Elem;
for (var i = 0; i < alltags.length; i++) {
Elem = Alltags[i];
if (Regex.test (elem.classname)) {//to detect the class name based on the regular
Matchelements.push (Elem);
}
}

return matchelements;
}
window[Susa] [getelementsbyclassname] = Getelementsbyclassname;

/*
* Toggledisplay method to toggle the visibility of HTML tags
*/
function Toggledisplay (ID, value) {
var Elem = $ (ID);
if (Elem!= $ (elem) | | elem = = NULL | | Elem.nodetype!= 1)
return false;
if (Elem.style.display!= "None") {
Elem.style.display = "None";
}
else {
Elem.style.display = value | | ;
}
return true;
}
window[Susa] ["toggledisplay"] = Toggledisplay;

/*
* InsertAfter Method
*/
function InsertAfter (node, referencenode) {
if (node!= $ (node) | | node = NULL)
return false;
if (Referencenode!= $ (referencenode) | | | referencenode = = NULL)
return false;

Return ReferenceNode.parentNode.insertBefore (node, referencenode.nextsibling); Note Use the InsertBefore method if the second argument
}//Is NULL, then inserted at the end of the ParentNode
window[Susa] [InsertAfter] = InsertAfter;

/*
* Removechildren method to delete all child elements under the current node
*/
function Removechildren (parent) {
if (parent!= $ (node) | | parent = NULL)
return false;
while (Parent.firstchild) {//Loop delete node
Parent.firstChild.parentNode.removeChild (Node.firstchild);
}
return to parent;
}
window[Susa] [removechildren] = Removechildren;

/*
* PrependChild method, insert the selected node to the front of the current node
*/
function PrependChild (parent, NewNode) {
if (parent!= $ (parent) | | parent = NULL)
return false;
if (NewNode!= $ (newNode) | | | newNode = = NULL)
return false;

if (parent.firstchild) {//When a child function is judged
Parent.insertbefore (NewNode, parent.firstchild);
}
else {
Parent.appendchild (NewNode);
}
return to parent;
}
window[Susa] [prependchild] = PrependChild;

/*
* Bindfunction () method for adjusting the execution environment of this
*/
function Adjustfunc (obj, func) {//Adjust the execution environment of func to obj
return function () {//Returns a reference to an anonymous function
Func.apply (obj, arguments);
};
}
window[Susa] [adjustfunc] = Adjustfunc;

/*
* Gets the width and height of the display window, returns an object that contains the width and height properties, is not exposed, and is called only in this anonymous function for other methods
*/
function Getbrowserwindowsize () {
var de = document.documentelement; Get root node
var obj = {
Width: (window.innerwidth | | (de.clientwidth) | | Document.body.clientWidth),
Height: (window.innerheight | | (de.clientheight) | | Document.body.clientHeight)
}

return obj;
}

/*
* Debug Log Object
*/
function log (ID) {
id = ID | | Susalogwindow;
var logwindow = null; Private properties, used in individual
var CreateWindow = function () {//private method, used to dynamically generate a list node
if (!document.body) {
Alert (document.body hasn\ t finished loading.);
Return
}
var browerwindowsize = Getbrowserwindowsize ();
var top = ((browerwindowsize.height-200)/2) | | 0; To get a new window placed in the middle of the browser is the position in the upper left corner
var left = ((browerwindowsize.width-200)/2) | | 0;

Logwindow = Document.createelement (UL); Dynamically generate a UL element
Logwindow.setattribute (ID, id);

LogWindow.style.position = absolute; Modifier UL Element
LogWindow.style.top = top + px;
LogWindow.style.left = left + px;

LogWindow.style.width = 250px;
LogWindow.style.height = 200px;
LogWindow.style.overflow = scroll;

logWindow.style.padding = 0;
LogWindow.style.margin = 0;
LogWindow.style.border = 1px solid black;
LogWindow.style.backgroundColor = white;
LogWindow.style.listStyle = none;
LogWindow.style.font = 10px/10px Verdana,tahoma,sans;

Document.body.appendChild (Logwindow); To add a dynamically generated node to the body
}

This.writeraw = function (message) {//privileged method, used to add Li content to the UL node generated by the CreateWindow method, you need to declare an instance to invoke
if (!logwindow)
CreateWindow (); If the initial window does not exist, it is created
var li = document.createelement ("Li"); Dynamically generating an LI element
li.style.padding = 2px;
Li.style.border = 0;
Li.style.borderBottom = 1px dotted black;
Li.style.margin = 0 2px;
Li.style.color = #000;
Li.style.font = 9px/9px Verdana,tahoma,sans;

if (typeof message = = undefined) {
Li.appendchild (document.createTextNode (message is undefined!));
}
Else
if (typeof li.innerhtml!= undefined) {
li.innerhtml = message;
}
else {
Li.appendchild (document.createTextNode (message));
}

Logwindow.appendchild (LI); Add the generated Li node to the Logwindow
return true;
}
}

Log.prototype = {
Write:function (message) {
if (Arguments.length = = 0) {//warning message parameter is NULL
Return This.writeraw ("Lack of params!");
}

if (typeof message!= "string") {//If the passed-in argument is not a string, attempt to invoke the ToString method, if the access is not present, record the object type
if (message.tostring)
Return This.writeraw (Message.tostring ()); Note This method of judgment: Message.tostring. Determines whether an object contains a property
Else
Return This.writeraw (typeof message);
}
Message = Message.replace (/</g, "<"). Replace (/>/g, ">"); Filter <> Left angle bracket
return This.writeraw (message);
},
Header:function (message) {//write a caption to the log window
message =--> <span style= "color:red; Background: #eee; Font-weight:bold; " > + message + </span> <--;
return This.writeraw (message);
}
}
window[Susa] [log] = new log (); Note to display the Declaration object because the reference to the privileged method this is used in the constructor
/*
* Self-created debugging function (original), to test the function name as debug parameters can support multiple parameters//(original)
*/
function Debug () {
for (var i = 0; i < arguments.length; i++) {
if (typeof Arguments[i]!= function) {
Alert ("Params sould be Function type!");
Return
}
}
var args = arguments;

(function () {//Encapsulate execution functions procedure
try {
for (var i = 0; i < args.length; i++) {
Args[i] (); Execution function
}
}
catch (ex) {
Susa.log.writeRaw (Error: + ex.message + "line:" + ex.linenumber);
}
})();
}
window[Susa] [debug] = Debug;

/*
* Declaring and determining the node type constant//original
*/
window[Susa [Node] = {
Element_node:1,
Attribute_node:2,
Text_node:3,
Cdata_section_node:4,
Entity_reference_node:5,
Entity_node:6,
Procession_instruction_node:7,
Comment_node:8,
Document_node:9,
Document_type_node:10,
Document_fragment_node:11,
Notation_node:12
};

/*
* function to detect the degree to which the browser supports DOM level (original)
*/
function Checkdomlevel () {
if (document.implementation) {//To determine whether the Document.implementation attribute is supported
var DOM = ["Core", "XML", "HTML", "views", "Sytlesheets", "CSS", "CSS2", "Events", "uievents", "mouseevents", "Mutationeve NT "," Htmlevents "," Range "," Traversal "," LS "," Ls-async "," Validation "];
var level = ["1.0", "2.0", "3.0"];

for (var i = 0; i < dom.length; i++) {
for (var j = 0; J < Level.length; J + +) {
if (Document.implementation.hasFeature (Dom[i], level[j]) {//document.implementation.hasfeature Accept two parameters
Susa.log.writeRaw ("<span style= color: #0c0; >dom "+ level[j] +" "+ Dom[i] +" supported.</span> ");
}
else {
Susa.log.writeRaw ("<span style= color: #c00; >dom "+ level[j] +" "+ Dom[i] +" not supported!</span> ")
}
}
}
}
else {
Susa.log.write ("<span style= color: #c00; ><b>no domimplementation supported!</b></span> ");
}
}
window[Susa] [checkdomlevel] = Checkdomlevel;

/*
* Gets and sets the value of the element attribute, which can be called by the getter and the way the setter is set
*/
function attr (elem, name, value) {
if (!name | | name.constructor!= String)
return;

Check that name is in a weird-named scenario
Name = {
For:htmlfor,
Class:classname
}[name] | |
Name

if (typeof value!= undefined) {
Elem[name] = value; Use Shortcuts first
if (Elem.setattribute) {//if possible, use setattribute
Elem.setattribute (name, value);
}
}
return Elem[name] | | Elem.getattribute (name) | | ; Returns the value of an attribute
}
window[Susa] [attr] = attr;

/*
* Common functions for creating new DOM elements
*/
function Create (label) {
Return document.createattributens? Document.createelementns (http://www.w3.org/1999/xhtml, label): document.createelement (label); Returns a reference to a new element
}
window[Susa [Create] = create;

/*
* Create Textnode node function
*/
function CreateText (elem) {//directly for DOM element invocation
$ (elem) ==elem? This.appendchild (Elem): This.appendchild (document.createTextNode (elem));
return this;
//}
function CreateText (parent, Elem) {//(reference + original)
return $ (elem) = = Elem? Parent.appendchild (Elem): Parent.appendchild (document.createTextNode (elem));
}
window["Susa" [createtext] = CreateText;

/*
* Insert element//(reference + original) before another DOM element
*/
function before (NewNode, Referencenode) {

if (!newnode && $ (referencenode)!= Referencenode)
return false;
var elems = Checkelem (NewNode); Get the array you want to add the node reference to
for (var i = elems.length-1 i >= 0; i--) {
ReferenceNode.parentNode.insertBefore (Elems[i], referencenode);
}
}
window[Susa] [before] = before;

/*
* Append a child element to another element, Elem can be a string with an HTML tag, or you can make a DOM element node reference//(reference + original)
*/
function append (parent, elem) {
if (!elem && $ (parent)!= parent)
return false;
var elems = Checkelem (elem); Get the array you want to add the node reference to
for (var i = elems.length-1 i >= 0; i--) {
Parent.appendchild (Elems[i]);
}
}
window[Susa] [Append] = append;

function Checkelem (elem) {//before and append function auxiliary functions//(reference + original)
var r = [];
if (elem && elem.constructor = = string) {//If the argument is a string
var div = Create ("div");
div.innerhtml = Elem;
for (var i = div.childnodes.length-1 i >= 0; i--) {
R[r.length] = div.childnodes[i]; Methods of dynamically generating arrays
}
}
Else
if (elem && elem.constructor = = array) {//If the argument is an array
var div = Create ("div");
div.innerhtml = Elem.join ();
for (var i = div.childnodes.length-1 i >= 0; i--) {
R[r.length] = div.childnodes[i]; Methods of dynamically generating arrays
}
}
Else
if (Elem && $ (elem) = = Elem) {//If it is a DOM node
R[r.length] = Elem;
}
return R;
}

/*
* Delete the entire contents of the DOM element, the parameter can make the DOM node reference, can also be the HTML ID label
*/
function Empty (elem) {
Elem = Transformlabelid (elem);
while (Elem.firstchild) {
Elem.removechild (Elem.firstchild);
}
}
window["Susa" [Empty] = empty;

/*
* HTML function that can be used to getting and Setting,elem DOM elements can be a string or a reference to a DOM element//(original)
*/
function html (parent, Elem) {
Parent = Transformlabelid (parent);
if (Elem && $ (elem) = = Elem) {
parent.innerhtml = elem.innerhtml;
return to parent;
}
else {
return Elem && Elem.constructor = = String? parent.innerhtml = Elem:parent.innerHTML;
}
}
window["Susa" ["html"] = HTML;

/*
* Get the universal function of the element text content, getting and setting can all
*/
function text (e) {
E = Transformlabelid (e);
if (Arguments[1]) {
e.innerhtml = arguments[1];
}
else {
var t = "";
E = E.childnodes | | E If the element is passed in, it continues to traverse its child elements, otherwise it is assumed to be an array
for (var j = 0; J < E.length; J + +) {
T + + E[j].nodetype!= 1? E[j].nodevalue:text (E[j]); Call the text function recursively
}
return t;
}
}
window[Susa] [text] = text;

/*
* Similar to innerHTML and innertext outerhtml and Outertext method/original
*/
function Outertext (Elem, t) {
Elem = Transformlabelid (elem);
To see if it is a DOM node or a text string
if (t) {
var el = T.constructor = String? document.createTextNode (t): t;
Elem.parentNode.insertBefore (el, Elem); Inserts a node before the current element
Elem.parentNode.removeChild (Elem); And then delete the current node
}
else {
Return text (elem); If the second argument is empty, the current text is returned
}

}
function outerHTML (Elem, h) {
Elem = Transformlabelid (elem);
if (h) {
var elems = Checkelem (h); Returns an array of H-string or node
for (var i = elems.length-1 i >= 0; i--) {
Elem.parentNode.insertBefore (Elems[i], elem);
}
Elem.parentNode.removeChild (Elem);
}
else {
var div = Create ("div");
Div.appendchild (Elem);
return div.innerhtml;
}
}
window["Susa" ["outertext"] = outertext;
window[Susa] ["outerhtml"] = outerhtml;

/*
* Wrag to outsource the current element with another element//original
*/
function Wrag (Elem, Wraglabel, Attrprop) {
Elem = Transformlabelid (elem);
var next = elem.nextsibling | | Document.body; Gets the next adjacent element of the Elem element, which is set to body if it does not exist
var w = create (Wraglabel); Generates a new element to contain the current element
for (Var o in Attrprop) {//Set properties for new element
W.setattribute (o, Attrprop[o]);
}
W.appendchild (Elem);
Next = = Document.body? Document.body.appendChild (W): Next.parentNode.insertBefore (w, next); Insert the containing element into the document
}
window["Susa" ["wrag"] = Wrag;

/*
* Conversion parameters for HTML ID tag for DOM node reference//Original
*/
function Transformlabelid (str) {
Return!STR? False: $ (str);
}

/*
* Delete a single DOM node, parameter can be a node reference, can also be HTML ID Tag value//(original)
*/
function Remove (elem) {
Transformlabelid (Elem). Parentnode.removechild (Transformlabelid (elem));
}
window[Susa [Remove] = remove;

/*
* A clone function that returns a copy of the DOM element, which can be either a node reference or an HTML ID tag value//(original)
*/
function Clone (elem) {
Return Transformlabelid (Elem). CloneNode (True);
}
window[Susa [Clone] = clone;

/*
* Common functions to block time bubbles
*/
function Stopbubble (e) {
if (e && e.stoppropagation) {//If parameters are passed in, then the method of the Consortium
E.stoppropagation ();
}
else {
Window.event.cancelBubble = true; The method of IE
}
}
window[Susa] [stopbubble] = stopbubble;

/*
* Common functions that prevent default browser behavior from occurring
*/
function Stopdefault (e) {
if (e && e.preventdefault) {//w3c method
E.preventdefault ();
}
else {
Window.event.returnValue = false; ie method
}
return false;
}
window["Susa" ["stopdefault"] = Stopdefault;

/*
* function to get the real and final CSS style attribute value of the element
*/
function GetStyle (elem, name) {
Elem = Transformlabelid (elem); The parameter elem can be either a DOM reference or a
if (Elem.style[name]) {//If the attribute exists with style[], then it has been set (and is current)
return Elem.style[name];
}
Else
if (Elem.currentstyle) {//Otherwise, the method of trying to use IE
return Elem.currentstyle[name];
}
Else
if (Document.defaultview && document.defaultView.getComputedStyle) {//or the method of the consortium, if present
It uses a generic ' text-align ' style rule rather than a textalign
name = Name.replace ([[A-z])/g, "-$1");
Name = Name.tolowercase ();
Return Document.defaultView.getComputedStyle (Elem, null). GetPropertyValue (name);

}
else {
return null;
}
}
window["Susa" [getstyle] = GetStyle;

/*
* Convert Word-word to Wordword Format function
*/
function Camelize (s) {
Return S.replace (/-(\w)/g, function (Strmatch, p) {
return P.touppercase ();
});
}

/*
* Set the CSS style of the element, parameter is an object (original)
*/
function SetStyle (elem, obj) {
Elem = Transformlabelid (elem);
for (var o in obj) {//traverse the properties of the obj parameter
Elem.style[o] = Obj[o]; Set the style style for a CSS
}
}
window[Susa] [setStyle] = SetStyle;

/*
* CSS functions, but getter and setter, return a specific element of CSS style//(original)
*/
function css (elem, obj) {
Elem = Transformlabelid (elem);
if (Elem && (typeof obj = "string")) {
Return GetStyle (Elem, obj); Call the GetStyle function to get the value of a particular CSS style
}
Else
if (typeof obj = = "Object") {
for (var o in obj) {
Elem.style[o] = Obj[o];
}
}
}
window[Susa [CSS] = CSS;

/*
* Merging two objects and merging the results into the first object//original
*/
function Mergeobj (obj1, obj2) {
if ((typeof obj1 = = "Object") && (typeof obj2 = = "Object")
return false;
for (Var o in obj2) {
Obj1[o] = Obj2[o];
}
return obj1;
}
window["Susa" ["mergeobj"] = mergeobj;

/*
* Pass in several function references, take the nearest function with no errors and execute (original)
*/
function $try () {
for (var i = 0; i < arguments.length; i++) {
try {
return arguments[i] (); To perform a parameter function
}
catch (ex) {
Continue
}
}
}
window["Susa" ["$try"] = $try;
Current 1/2 page 12 Next read the full text

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.