Common javascript Functions on the AppBaseJs class library and _ js object-oriented functions written by other js Class Libraries

Source: Internet
Author: User
Tags set cookie
AppBaseJs class library. It is written based on common functions on the Internet and other js class libraries for your convenience. The Code is as follows:


/*-----------------------------------
Web Application JavaScript Library
2009.11 janchie
------------------------------------*/

// String native object extension left and right Spaces
String. prototype. trim = function (){
Return this. replace (/(^ [\ s \ n \ t \ r] *) | ([\ s \ n \ r \ t] * $)/g ,"");
};
// Date native object extended formatting output
Date. prototype. format = function (string ){
Var self = this;
Var p = function p (s ){
Return (s. toString (). length = 1 )? "0" + s: s;
};
Return string? String. replace (/dd? D? D? | MM? M? M? | Yy? Y? Y? | Hh? | HH? | Mm? | Ss? | Tt? | Zz? Z? /G,
Function (string ){
Switch (string ){
Case "hh": return p (self. getHours () <13? Self. getHours (): (self. getHours ()-12 ));
Case "h": return self. getHours () <13? Self. getHours (): (self. getHours ()-12 );
Case "HH": return p (self. getHours ());
Case "H": return self. getHours ();
Case "mm": return p (self. getMinutes ());
Case "m": return self. getMinutes ();
Case "ss": return p (self. getSeconds ());
Case "s": return self. getSeconds ();
Case "yyyy": return self. getFullYear ();
Case "yy": return self. getFullYear (). toString (). substring (2, 4 );
Case "dddd": return self. getDayName ();
Case "ddd": return self. getDayName (true );
Case "dd": return p (self. getDate ());
Case "d": return self. getDate (). toString ();
Case "MMMM": return self. getMonthName ();
Case "MMM": return self. getMonthName (true );
Case "MM": return p (self. getMonth () + 1 ));
Case "M": return self. getMonth () + 1;
Case "t": return self. getHours () <12? Date. CultureInfo. amDesignator. substring (0, 1): Date. CultureInfo. pmDesignator. substring (0, 1 );
Case "tt": return self. getHours () <12? Date. CultureInfo. amDesignator: Date. CultureInfo. pmDesignator;
Case "zzz ":
Case "zz ":
Case "z": return "";
}
}): This. toString ();
};
/*------------------------------------*/

// Declare the object
Var App = {};
// Object Inheritance or attribute Merging
App. extend = function (obj, hash ){
This. each (hash, function (key, value ){
Obj [key] = value;
});
Return obj;
};
// Traverse
App. each = function (obj, func, context ){
Var length = obj. length, I =-1;
If (length! = Undefined ){
While (++ I <length) if (func. call (context, obj [I], I, obj, length) = false) break;
}
Else for (var key in obj) if (obj. hasOwnProperty (key) if (func. call (context, key, obj [key], obj) = false) break;
Return obj;
};
(Function (doc, win ){
Var string = Object. prototype. toString,
Quirks = doc. compatMode = "BackCompat ",
Docelem = doc.doc umentElement,
Ua = win. navigator. userAgent. toLowerCase (),
Version = (ua. match (/.(? : Rv | it | ra | ie) [\/:] ([\ d.] +)/) | []) [1],
IsChrome =/chrome/. test (ua ),
IsWebKit =/webkit/. test (ua ),
IsSafari =! IsChrome & isWebKit,
IsOpera =/opera/. test (ua ),
IsIE =/msie/. test (ua )&&! IsOpera,
IsFF =/firefox/. test (ua );
// Dom Loading
Doc. ready = function (func ){
Var isReady = false, doReady = function (){
If (isReady) return;
IsReady = true; func ();
};
If (isIE ){
If (docelem. doScroll & win. self = win. top ){
(Function (){
If (isReady) return;
Try {
Docelem. doScroll ("left ");
} Catch (error ){
SetTimeout (arguments. callee, 0 );
Return;
}
DoReady ();
})();
} Else {
If (isReady) return;
This. attachEvent ("onreadystatechange", function (){
If (doc. readyState = "complete "){
Doc. detachEvent ("onreadystatechange", arguments. callee );
DoReady ();
}
});
}
Win. attachEvent ('onload', doReady );
} Else if (isWebKit & version <525 ){
(Function (){
If (isReady) return;
If (/loaded | complete/. test (doc. readyState ))
DoReady ();
Else
SetTimeout (arguments. callee, 0 );
})();
Win. addEventListener ('load', doReady, false );
} Else {
If (! IsFF)
This. addEventListener ("DOMContentLoaded", function (){
Doc. removeEventListener ("DOMContentLoaded", arguments. callee, false );
DoReady ();
}, False );
This. addEventListener ('load', doReady, false );
}
};
App. extend (App ,{
// Type detection
IsArray: function (v) {// whether it is an array
Return string. apply (v) = "[object Array]";
},
IsFunction: function (v) {// whether it is a function body
Return string. apply (v) = "[object Function]";
},
IsNumber: function (v) {// whether it is a number
Return typeof v = "number" & isFinite (v );
},
IsDate: function (v) {// whether it is a date
Return string. apply (v) = "[object Date]";
},
IsElement: function (v) {// whether it is a Dom Element Node
Return !! (V & v. nodeType = 1 );
},
// Browser Detection
IsOpera: isOpera,
IsChrome: isChrome,
IsWebKit: isWebKit,
IsSafari: isSafari,
IsIE: isIE,
IsFF: isFF,
IsQuirks: quirks,
GetVersion: version,

// Obtain the id Element
$: Function (id ){
Return typeof id = "string "? Doc. getElementById (id): id;
},
// Retrieve the name Element Set
$ N: function (name ){
Return doc. getElementsByName (name );
},
// Retrieve the tag Element Set
$ T: function (tag, root ){
Return (root | doc). getElementsByTagName (tag );
},
// Set elements by attribute name (include or not), value, and range
$ A: function (attrName, attrValue, tag, root ){
Var elems = doc. all? Doc. all: this. $ T (tag | "*", root | doc), result = [],
AttVal = (typeof attrValue! = "Undefined ")? New RegExp ("(^ | \ s)" + attrValue + "(\ s | $)"): null;
For (var I = 0; I Attr = elems [I] [attrName] | elems [I]. getAttribute (attrName );
If (typeof attr = "string" & attr. length> 0 ){
If (typeof attrValue = "undefined" | (attVal & attVal. test (attr ))){
Result. push (elems [I]);
}
}
}
Return result;
},
// Retrieve the body Element
$ B: doc. body | docelem,
// Obtains the Class attribute element set.
$ C: function (attrValue, tag, root ){
Return this. $ A ("className", attrValue, tag, root );
},
// Retrieve the browser form width
GetWinWidth: win. innerWidth | docelem. clientWidth | doc. body. clientWidth,
// Retrieve the height of the browser form
GetWinHeight: win. innerHeight | docelem. clientHeight | doc. body. clientHeight,
// Retrieve the element style
GetStyle: function (elem, name ){
If (elem. style [name]) {
Return elem. style [name];
} Else if (elem. currentStyle ){
Return elem. currentStyle [name];
} Else if (doc. defaultView & doc. defaultView. getComputedStyle ){
Name = name. replace (/([A-Z])/g, "-$1 ");
Name = name. toLowerCase ();
Var s = doc. defaultView. getComputedStyle (elem ,"");
Return s & s. getPropertyValue (name );
} Else {
Return null;
}
},
// Obtain the screen coordinate value of an element
GetPosition: function (){
Return docelem. getBoundingClientRect & function (o ){
Var pos = o. getBoundingClientRect (), root = o. ownerDocument | o.doc;
Return {left: pos.left?root.doc umentElement. scrollLeft, top: pos.top=root.doc umentElement. scrollTop };
} | Function (o ){
Var x = 0, y = 0;
Do {x + = o. offsetLeft; y + = o. offsetTop;} while (o = o. offsetParent ));
Return {left: x, top: y };
};
}(),
// Set transparency
SetOpacity: function (elem, num ){
If (elem. filters ){
Elem. style. filter = "alpha (opacity =" + num + ")";
} Else {
Elem. style. opacity = num/100;
}
},
// Hide or display elements
Hide: function (elem) {elem. style. display = "none ";},
Show: function (elem) {elem. style. display = "block ";},
Toggle: function (elem ){
Elem. style. display = this. getStyle (elem, "display") = "none "? "Block": "none ";
},
// Element Class attribute operation
AddClass: function (elem, clsName ){
If (elem. className = ''){
Elem. className = clsName;
} Else if (elem. className! = ''& ('' + Elem. className + ''). indexOf ('' + clsName + '') ===-1 ){
Elem. className = elem. className + ''+ clsName;
}
},
RemoveClass: function (elem, clsName ){
If (clsName & (''+ elem. className +''). indexOf (''+ clsName +'')>-1 ){
Elem. className = (''+ elem. className + ''). replace (''+ clsName + '',''). replace (/^ | $/g ,'');
}
},
// Append an Html text object (Table supported)
Append: function (elem, text ){
If (typeof text = "string "){
If (elem. insertAdjacentHTML ){
If (elem. tagName = "TABLE "){
Var html = elem. outerHTML, ep = elem. parentNode, sl = html. length;
Text = html. substr (0, sl-8) + text + html. substr (sl-8, sl );
Ep. insertAdjacentHTML ("beforeEnd", text );
Ep. replaceChild (ep. lastChild, elem );
} Else {
Elem. insertAdjacentHTML ("beforeEnd", text );
}
} Else {
Var rlt = null, rg = doc. createRange (), fm = rg. createContextualFragment (text );
Rlt? Elem. insertBefore (fm, rlt): elem. appendChild (fm );
}
} Else if (typeof text = "object") elem. appendChild (text );
},
// Delete an element
Remove: function (elem ){
If (elem. parentNode) elem. parentNode. removeChild (elem );
},
// Empty element content and subnodes
Empty: function (elem ){
While (elem. firstChild ){
Elem. removeChild (elem. firstChild );
}
},
// Image pre-loading
Loadimages: function (){
Var a = arguments, loads = function (){
If (doc. images) {if (! Doc. ps) doc. ps = [];
Var I, j = doc. ps. length; for (I = 0; iif (a [I]. indexOf ("#")! = 0) {doc. ps [j] = new Image; doc. ps [j ++]. src = a [I] ;}}
};
Arguments. callee. caller? Loads (): doc. ready (loads );
},

// Event binding
Bind: function (){
If (win. addEventListener ){
Return function (elem, sType, fnc ){
Elem. addEventListener (sType, fnc, false );
};
} Else if (win. attachEvent ){
Return function (elem, sType, fnc ){
Elem. attachEvent ("on" + sType, fnc );
};
} Else {
Return function (){};
}
}(),
// Unbind the event
Unbind: function (elem, sType, fnc ){
If (elem. removeEventListener ){
Elem. removeEventListener (sType, fnc, false );
} Else if (elem. detachEvent ){
Elem. detachEvent ("on" + sType, fnc );
} Else {
Elem ["on" + sType] = null;
}
},
// Disable event bubbling
StopPropagation: function (ev ){
If (ev. stopPropagation ){
Ev. stopPropagation ();
} Else {
Ev. cancelBubble = true;
}
},
// Disable default event actions
PreventDefault: function (ev ){
If (ev. preventDefault ){
Ev. preventDefault ();
} Else {
Ev. returnValue = false;
}
},
// Obtain the mouse position
GetXY: function (ev ){
Return {
X: ev. pageX? Ev. pageX: ev. clientX + docelem. scrollLeft,
Y: ev. pageY? Ev. pageY: ev. clientY + docelem. scrollTop
};
},
// Bind the drag event
Drag: function (obj, obj2) {// obj: Moving Object obj2: drag point
Obj2 = obj2 | obj; // if no drag point is set, the drag point is the object to move.
Var x, y, ut = this;
Obj2.onmousedown = function (e ){
E = e | win. event;
Ut. preventDefault (e );
Obj. setCapture & obj. setCapture ();
X = ut. getXY (e). x-parseInt (obj. style. left );
Y = ut. getXY (e). y-parseInt (obj. style. top );
Docelem. onmousemove = over;
Docelem. onmouseup = up;
}
Function over (e ){
E = e | win. event;
Obj. style. left = ut. getXY (e). x-x + "px ";
Obj. style. top = ut. getXY (e). y-y + "px ";
}
Function up (){
Obj. releaseCapture & obj. releaseCapture ();
Docelem. onmousemove = null;
Docelem. onmouseup = null;
}
},
// Bind a Horizontal Rolling event
SliderX: function (obj, x1, x2, overEvent, upEvent ){
Var x, t, ut = this;
Obj. onmousedown = function (e ){
E = e | win. event;
Ut. preventDefault (e );
Obj. setCapture & obj. setCapture ();
T = ut. getXY (e). x-parseInt (obj. style. left );
Docelem. onmousemove = over;
Docelem. onmouseup = up;
}
Function over (e ){
E = e | win. event;
X = ut. getXY (e). x-t;
If (x If (x> x2) x = x2;
Obj. style. left = x + "px ";
OverEvent & overEvent (x );
}
Function up (){
Obj. releaseCapture & obj. releaseCapture ();
Docelem. onmousemove = null;
Docelem. onmouseup = null;
UpEvent & upEvent (x );
}
},
// Bind a vertical rolling event
SliderY: function (obj, y1, y2, overEvent, upEvent ){
Var y, t, ut = this;
Obj. onmousedown = function (e ){
E = e | win. event;
Ut. preventDefault (e );
Obj. setCapture & obj. setCapture ();
T = ut. getXY (e). y-parseInt (obj. style. top );
Docelem. onmousemove = over;
Docelem. onmouseup = up;
}
Function over (e ){
E = e | win. event;
Y = ut. getXY (e). y-t;
If (y If (y> y2) y = y2;
Obj. style. top = y + "px ";
OverEvent & overEvent (y );
}
Function up (){
Obj. releaseCapture & obj. releaseCapture ();
Docelem. onmousemove = null;
Docelem. onmouseup = null;
UpEvent & upEvent (y );
}
},
// Set cookie
SetCookie: function (n, v, t ){
Var exp = new Date ();
Exp. setTime (exp. getTime () + (t | 24) x 60*60*1000 );
Doc. cookie = n + "=" + escape (v) + "; expires =" + exp. toGMTString () + '; path = /';
},
// Obtain the cookie
GetCookie: function (n ){
Var arr = doc. cookie. match (new RegExp ("(^ |)" + n + "= ([^;] *) (; | $ )"));
If (arr! = Null) return unescape (arr [2]);
Return null;
}
});
}) (Document, window );

// Convert a date string to a date
App. parseDate = function (date ){
Var dt = date instanceof Date? Date: Date (date. replace ("-","/"));
Return isNaN (dt. getTime ())? Null: dt;
};
// Convert a Json string to an object
App. parseJSON = function (jsonString ){
Var result = false;
Try {
Result = eval ('+ jsonString + ')');
} Catch (e ){};
Return result;
};
// Unique value not repeated
App. getUid = function (){
Return "uid" + (new Date (). getTime () + parseInt (Math. random () * 100000 );
};
// Obtain the random number in the specified range
App. random = function (n1, n2 ){
Return Math. floor (Math. random () * (n2-n1 + 1) + n1;
};
// Second to millisecond
App. s2ms = function (str ){
Var t = str. split (":");
Return t [0] * 60000 + t [1] * 1000;
};
// Converts a millisecond value to a second.
App. ms2s = function (MS ){
Return (ms/60000 + ":" + ms/1000% 60 ). replace (/\. \ d +/g ,""). replace (/(^ |:) (\ d )(?! \ D)/g, "$10 $2 ");
};
// Convert numbers to numbers
App. num2number = function (num, n ){
Return Array (n). join ("0"). concat (num). slice (-n );
};
// Convert numbers to Chinese
App. num2gb = function (n ){
Return "0 February 5, 1234". split ("") [n];
};
// Flash Generation Code
App. getFlash = function (url, width, height, param ){
Var tagName = "", o1 = {width: width | 1, height: height | 1}, o2 = {};
If (this. isIE ){
TagName = "object ";
O1.classid = "clsid: D27CDB6E-AE6D-11cf-96B8-444553540000 ";
O1.codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0 ";
O2.movie = url;
O2.quality = "high ";
Param & this. extend (o2, param );
} Else {
TagName = "embed ";
O1.type = "application/x-shockwave-flash ";
O1.pluginspage = "http://www.adobe.com/go/getflashplayer_cn ";
O1.src = url;
O1.quality = "high ";
Param & this. extend (o1, param );
}
If (o1.width <2 & o1.height <2) tagName + = 'style = "position: absolute; top:-100px ;"';
Var a1 = [], a2 = [], I;
For (I in o1) a1.push (I + '= "' + o1 [I] + '"');
For (I in o2) a2.push (' ');
Return '<' + tagName + a1.join ('') + '>' + a2.join ('') +' ';
};
// Code generated by the player
App. getPlayer = function (url, width, height, param ){
Var wmp = ["6bf52a52-394a-11d3-b153-00c04f79faa6", "application/x-mplayer2"];
Var rmp = ["CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA", "audio/x-pn-realaudio-plugin"];
Var mp =/\. rm $/. test (url )? Rmp: wmp;
Var tagName = "", o1 = {width: width | 1, height: height | 1}, o2 = {};
If (this. isIE ){
TagName = "object ";
O1.classid = "clsid:" + mp [0];
O2.url = url;
Param & this. extend (o2, param );
} Else {
TagName = "embed ";
O1.type = mp [1];
O1.src = url;
Param & this. extend (o1, param );
}
If (o1.width <2 & o1.height <2) tagName + = 'style = "position: absolute; top:-100px ;"';
Var a1 = [], a2 = [], I;
For (I in o1) a1.push (I + '= "' + o1 [I] + '"');
For (I in o2) a2.push (' ');
Return '<' + tagName + a1.join ('') + '>' + a2.join ('') +' ';
};
// Obtain the XMLHttp object
App. xmlhttp = function (){
If (this. isFF) return new XMLHttpRequest ();
Var a = ["Msxml2.XMLHTTP. 3.0", "Msxml2.XMLHTTP", "Microsoft. XMLHTTP", "Msxml2.XMLHTTP. 4.0", "Msxml2.XMLHTTP. 5.0"];
For (var I = 0, l = a. length; I Try {
Return new ActiveXObject (a [I]);
} Catch (e ){}
}
Return false;
};
// Get data
App. get = function (url, callBack ){
Var x = this. xmlhttp ();
X. open ("get", url, true );
X. onreadystatechange = function (){
X. readyState = 4 & (x. status = 0 | x. status = 200) & callBack (x. responseText );
}
X. send (null );
};
// Post Data
App. post = function (url, arg, callBack ){
Var x = this. xmlhttp ();
X. open ("post", url, true );
X. setRequestHeader ("Content-Length", arg. length );
X. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
X. onreadystatechange = function (){
X. readyState = 4 & (x. status = 0 | x. status = 200) & callBack (x. responseText );
}
X. send (arg );
};


A small number of functions are not tested. You are welcome to give your comments.
Related Article

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.