JavaScript application library code_javascript skills
/* $ Get the specified object
@element object name
You can use the object name collection, and the return value is the collection of objects
If you use the Prototype class library, please put This function comments out all functions that also implement this function in
Sams_object.Get()
*/
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i elements.push($(arguments[i]));
return elements;
}
if (typeof element == 'string')
element = document.getElementById(element);
return element;
}
/// Browser related operations
var Sams_browse = {
/* Check browsing information */
checkBrowser : function ()
{
this.ver=navigator.appVersion
this.dom=document.getElementById?1:0
this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
this.ie5=(this.ver.indexOf("MSIE 5" )>-1 && this.dom)?1:0;
this.ie4=(document.all && !this.dom)?1:0;
this.ns5=(this.dom && parseInt( this.ver) >= 5) ?1:0;
this.ns4=(document.layers && !this.dom)?1:0;
this.mac=(this.ver.indexOf(' Mac') > -1) ?1:0;
this.ope=(navigator.userAgent.indexOf('Opera')>-1);
this.ie=(this.ie6 || this. ie5 || this.ie4)
this.ns=(this.ns4 || this.ns5)
this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope)
this.nbw=(!this.bw)
return this;
},
/* Set to Homepage
@url The address to be set as the homepage
*/
SetDefault: function ()
{
this.style.behavior='url(#default#homepage)';
this.setHomePage(this.GetUrl());
return false;
},
/* Copy the specified URL address
@Msg The character set to be written to the clipboard
*/
SetCopy : function (Msg){
if(navigator.userAgent.toLowerCase().indexOf('ie') > -1) {
clipboardData.setData('Text',Msg) ;
alert ("Website address "" Msg "" Copied to your clipboard You can use the Ctrl V shortcut key to paste it where you need it");
}
else
{
prompt("Please copy the website address:",Msg);
}
},
/* Add to favorites
@site Site name
@url Address
*/
AddBookmark: function (site, url){
if(navigator.userAgent .toLowerCase().indexOf('ie') > -1) {
window.external.addFavorite(url,site)
} else if (navigator.userAgent.toLowerCase().indexOf('opera') > -1) {
alert ("Please use Ctrl T to add this page to your favorites");
} else {
alert ("Please use Ctrl D to add this page to your favorites");
}
},
/* Open the window with the width and height specified by Url */
OpenWindows: function (url,width,height)
{
window.open( url,'newwin','width=' width ',height=' height);
return false;
},
/* Disable browser Javascript error prompts */
CloseError : function(){
window.onerror = function(){return true;};
},
/* Get browser URL */
GetUrl : function(){
return location.href;
},
/* Get URL parameters */
GetUrlParam: function(){
return location.search;
},
/* Get the page source */
GetFrom : function(){
return document.referrer;
},
/* Get the specified URL parameter value
@name Parameter name
*/
Request: function(name){
var GetUrl = this.GetUrl();
var Plist = new Array();
if(GetUrl.indexOf('?') > 0)
{
Plist = GetUrl.split('?')[1].split(' &');
}
else if(GetUrl.indexOf('#') > 0)
{
Plist = GetUrl.split('#')[1].split('& ');
}
if (GetUrl.length > 0)
{
for(var i=0; i
var GetValue = Plist[i].split('=');
if (GetValue[0].toUpperCase() == name.toUpperCase())
{
return GetValue[1];
break ;
}
}
return;
}
},
/* Directly write HTML to a new window
@title Title
@msg Content
*/
Popmsg : function PopIt(title,msg)
{
var popup = window.open('','popDialog','height=500,width=400,scrollbars=yes ');
popup.document.write('
popup.document.close();
}
};
/// Object operations
var Sams_object = {
/* Create a DIV object
@ID The ID of the object to be created
@ClassName The Class of the created object
@SetValue Set the value of the object
@ToDiv Append the object to the specified object. If the specified object does not exist, Then append after the Body
Return the created object
*/
CreateDiv : function (ID,ClassName,SetValue,ToDiv){
var createddiv = document.createElement('div');
if(ID != null) creatediv.id = ID;
creatediv.style.position = 'absolute';
if(ClassName != null) creatediv.className = ClassName;
if( this.Get(ToDiv))
{
this.Get(ToDiv).appendChild(creatediv);
}
else
{
document.getElementsByTagName('body')[ 0].appendChild(creatediv);
}
this.SetValue(ID,SetValue);
return this.Get(ID);
},
/* Delete specified DIV object
@objid Object ID to be deleted
Return Bool operation result
*/
DeleteDiv: function (objid)
{
try
{
if( this.Get(objid))
{
var GetParent = this.Get(objid).parentNode;
GetParent.removeChild(this.Get(objid));
return true;
}
else
{
return false;
}
}
catch(e)
{
return false;
}
},
/* Get the browser object
@id The object ID to be obtained
You can use the object name collection, and the return value is the collection of objects
*/
Get: function (objid) {
if (arguments.length > 1) {
for (var i = 0, objids = [], length = arguments.length; i objids.push(this.Get (arguments[i]));
return objids;
}
if (typeof objid == 'string')
{
if (document.getElementById) {
objid = document.getElementById(objid);
} else if (document.all) {
objid = document.all[objid];
} else if (document.layers) {
objid = document. layers[objid];
}
}
return objid;
},
/* Get the value of the object
@objid Object ID
*/
GetValue: function (objid) {
if (typeof objid == 'string')
{
var getTagName = this.Get(objid).tagName.toLowerCase();
if (getTagName == 'input' || getTagName == 'textarea' || getTagName == 'select')
{
return this.Get(objid).value;
}
else if (getTagName == 'div' || getTagName == 'span')
{
return this .Get(objid).innerText;
}
}
else if (typeof objid == 'object')
{
return objid.value;
}
} ,
/* Set the value of the specified object, and realize the direct assignment or clearing operation
@objid Object ID
@inserValue Pass in the value (optional Null: clear the value of the ID, then directly Assignment)
*/
SetValue: function(objid,inserValue) {
var getTagName = this.Get(objid).tagName.toLowerCase();
if (inserValue == null) insertValue = '';
if (getTagName == 'input' || getTagName == 'textarea')
{
this.Get(objid).value = insertValue;
}
else if (getTagName == 'div' || getTagName == 'sapn')
{
this.Get(objid).innerText = insertValue;
}
},
/* Copy object value to clipboard
@str Object value
*/
CopyCode: function (str) {
var rng = document.body.createTextRange();
rng .moveToElementText(str);
rng.scrollIntoView();
rng.select();
rng.execCommand("Copy");
rng.collapse(false);
} ,
/* Show and hide an object
@Objid Object ID
@isshow For specific operations, specify Obj as False: none or True: block (optional)
*/
ShowHidd : function(objid,isshow){
if (isshow != null)
{
if(isshow)
{
this.Get(objid).style.display = 'block ';
}
else
{
this.Get(objid).style.display = 'none';
}
}
else
{
if(this.Get(objid).style.display == 'none')
{
this.Get(objid).style.display = 'block';
}
else
{
this.Get(objid).style.display = 'none';
}
}
},
/* Whether the current object is visible
@ objid Object ID
*/
IsVisible : function(objid){
if(this.Get(objid))
{
try
{
if (this.Get (objid).style.display == 'none')
{
return false
}
if(this.Get(objid).style.visibility == 'hidden')
{ Return false;
}
Return True;
}
Catch (e)
{
Return false;
}
}
else
{
return false;
}
}
};
/// Character processing
var Sams_string = {
/* Take the specified value on the left The value of length
@str Character set to be processed
@n Length
*/
Left: function (str,n)
{
if (str.length > 0)
{
if(n>str.length) n = str.length;
return str.substr(0,n)
}
else
{
return;
}
},
/* Take the value of the specified length on the right
@str Character set to be processed
@n Length
*/
Right: function (str,n)
{
if(str.length > 0)
{
if(n>=str.length) return str;
return str.substr(str.length-n,n);
}
else
{
return;
}
},
/* Trim: Clear spaces on both sides
@str Character set to be processed
*/
Trim : function (str)
{
if (typeof str == 'string') return str.replace(/(^s*)|(s*$)/g, ' ');
},
/* LTrim: Clear the left space
@str Character set to be processed
*/
Ltrim: function (str)
{
if (typeof str == 'string') return str.replace(/(^s*)/g, '');
},
/* RTrim: Clear the space on the right
@str Character set to be processed
*/
Rtrim: function (str)
{
if (typeof str == 'string') return str.replace(/(s* $)/g, '');
},
/* Clear non-characters before and after
@str Character set to be processed
*/
strip: function(str ) {
if (typeof str == 'string') return str.replace(/^s /, '').replace(/(^s*)|(s*$)/g, '');
},
/* Filter the HTML tags in the characters
@str The character set to be processed
*/
stripTags: function(str) {
if (typeof str == 'string')return str.replace(/?[^>] >/gi, '').replace(/(^s*)|(s*$)/g, '');
}
};
/// Time-related operations
var Sams_time = {
/* Get today’s date yyyy-MM-dd */
GetDateNow : function (){
var d,y,m,dd;
d = new Date();
y = d.getYear();
m = d.getMonth() 1;
dd = d. getDate ();
@N Number of dates to add
*/
AddDays: function(toDate,N){
var aDate=this._cvtISOToDate(toDate);
if (!aDate) return " ";
var millis=86400000 * N;
aDate=new Date(aDate.getTime() millis);
return this._fmtDateISO(aDate);
},
_fmtDateISO : function (aDate) {
with (aDate) {
var mm=getMonth() 1;
if (mm var dd=getDate() ;
if (dd return (getFullYear() '-' mm '-' dd);
}
}, _cvtISOToDate : function (isoDate) {
var atomDate= isoDate.split('-'); var aDate=new Date(parseInt(atomDate[0],10),parseInt(atomDate[1],10)- 1,parseInt(atomDate[2],10),6,0,0);
return aDate;
}
};
/// Image related operations
var Sams_media = {
/* Add the middle mouse button zoom function for a single image. For batches, you can directly use ResizeImage (specify the image size to add this function: Int) (this function is only applicable to IE)
objid object ID
*/
ZoomFun : function(objid){
Sams_object.Get(objid).onmousewheel = function(){return Sams_media.imagecontrol(this);}
},
/* Reset the image size and add the zoom function (this function is only applicable to IE)
@IntSize Specify the size of the image
If it fits the image size, add the zoom function
* /
ResizeImage: function (IntSize) {
var imgsinlog=document.getElementsByTagName('img');
for(j=0; j
imgsinlog[j].width = IntSize;
imgsinlog[j].style.cursor= 'pointer';
imgsinlog[j].onclick = function( ) {window.open(this.src);}
if (navigator.userAgent.toLowerCase().indexOf('ie') > -1) {
imgsinlog[j].title = 'You can use Use the middle mouse button or use the Ctrl mouse wheel to zoom in on the image. Click on the image to open it in a new window';
imgsinlog[j].onmousewheel = function(){return Sams_media.imagecontrol(this);};
}
else
{
imgsinlog[j].title = 'Click on the image to open it in a new window';
}
}
}
},
imagecontrol : function( obj){
var zoom=parseInt(obj.style.zoom, 10)||100;zoom =event.wheelDelta/12;
if (zoom>0) obj.style.zoom=zoom '%' ;
return false;
},
/* If there is an exception such as the image cannot be downloaded, the error prompt image displayed
@errimgpath The image path of the error prompt
*/
ImagesError : function(errimgpath){
var imglist = document.getElementsByTagName('img');
for(j=0; j
this.src = errimgpath;
}
}
},
/* Display media
@mFile File path
@mFileType File type (can be empty, if it is Flash, specify the swf type)
@ObjID Object ID
@mWidth Displayed object width
@mHeight Displayed object height
Note: You can specify the object The ID, if the ID does not exist, will be automatically created and appended after the Body
*/
ShowMedia: function (mFile, mFileType, ObjID, mWidth, mHeight) {
var mediaStr;
switch( mFileType){
case "swf":
mediaStr="";
break;
default:
mediaStr="";
}
var mediaDiv = Sams_object.Get(ObjID);
if (mediaDiv) {
mediaDiv.innerHTML = mediaStr;
}
else
{
mediaDiv = document.createElement("div");
mediaDiv.id = ObjID;
mediaDiv.innerHTML = mediaStr;
document.getElementsByTagName('body')[0].appendChild(mediaDiv);
}
return false;
}
};
/// Style related operations
var Sams_style = {
/* Change font size
@objid Object ID
@size Font size
*/
doZoom : function (objid, size){
Sams_object.Get(objid).style.fontSize=size 'px';
},
/* Change the style of the specified object
@objid Object ID
@className ClassName to be changed
*/
ClassName: function(objid, className) {
Sams_object .Get(objid).className = className;
},
/* Object positioning
@obj The object to be positioned
Returns the array object of the X.Y result
*/
GotoXY : function (obj) {
var t=obj.offsetTop;
var l=obj.offsetLeft;
while(obj=obj.offsetParent){
t =obj.offsetTop;
l =obj.offsetLeft;
}
return Array(t,l);
}
};
/// Scientific Computing
var Sams_account = {
/* Calculate every 1 to 10
@ Value
*/
GetTen: function (i)
{
var items_One,Get_One;
if (i.length > 1&& (/^d $/.test(i)))
{
items_One = i.substr(0,i.length-1);
Get_One = i.substr(i.length-1 ,1);
if (parseInt(Get_One)>0)
{
items_One = parseInt(items_One) 1;
items_One = items_One '0';
}
el se
{
items_One = items_One '0';
}
}
else
{
items_One = i;
}
return items_One;
}
};
/// Data validation (all numerical return values are Bool type)
var Sams_validate = {
/* Whether it is numeric data
@str character set
*/
IsNumber : function(str){
if (/^d $/.test(str)){return true;}else{return false;}
},
/* Whether it is numeric data
@objid Object ID
*/
IsNumberObj: function(objid){
return this.IsNumber(Sams_object.GetValue(objid));
},
/* Is it a natural number data
@str Character set
*/
IsInt: function(str){
if (/^( |-)? d $/.test(str)){return true;}else{return false;}
},
/* Whether it is natural number data
@objid Object ID
*/
IsIntObj : function(objid){
return this.IsInt(Sams_object.GetValue(objid));
},
/* Whether it is a Chinese character
@str character set
*/
IsChinese : function(str)
{
if (/^[u4e00-u9fa5] $/.test(str)){return true;}else{return false;}
},
/* Is it a Chinese character? .GetValue(objid));
},
/* Whether it is an English letter
@str Character set
*/
IsLower: function(str)
{
if (/^[A-Za-z] $/.test(str)){return true}else{return false;}
},
/* Whether it is an English letter
@objid Object ID
*/
IsLowerObj : function(objid)
{
return this.IsLower(Sams_object.GetValue(objid));
},
/* Is it the correct URL
@str Character set
*/
IsUrl: function(str)
{
var myReg = /^((http:[/][/] )?w ([.]w |[/]w*)*)?$/;
if(myReg.test(str)){return true;}else{return false;}
},
/* Is it the correct URL? ));
},
/* Is it the correct email format?
@str Character set
*/
IsEmail: function(str)
{
var myReg = /^([-_A-Za-z0-9.] )@([_A-Za-z0-9] .) [A-Za-z0-9]{2,3}$/;
if(myReg.test(str)){return true;}else{return false;}
},
/* Is it the correct email format?
@objid Object ID
*/
IsEmailObj : function(objid)
{
return this.IsEmail(Sams_object.GetValue(objid));
},
/* Is it the correct mobile phone number?
@str Character set
*/
IsMobile: function(str)
{
var regu =/(^[ 1][3][0-9]{9}$)|(^0[1][3][0-9]{9}$)/;
var re = new RegExp(regu);
if (re.test(str)){return true;}else{return false;}
},
/* Is it the correct mobile phone number?
@objid Object ID
*/
IsMobileObj : function(objid)
{
return this.IsMobile(Sams_object.GetValue(objid));
}
};
/*
Implement Ajax function
Sams_ajax.SendRequest('GET', url, null, recall, "addtohome");
Sams_ajax.SendRequest('GET', url, null, null);
obj. responseText;
*/
var Sams_ajax = {
_objPool: [],
_getInstance: function (){
for (var i = 0; i . :function (){ if (window.XMLHttpRequest){
var objXMLHttp = new XMLHttpRequest();
}
else{
var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2 .XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for(var n = 0; n try {
var objXMLHttp = new ActiveXObject(MSXML[n]);
break;
}
objXMLHttp.readyState == null){
objXMLHttp.readyState = 4;
== "function"){
} return objXMLHttp;
},
/// 开始发送请求
SendRequest : function (method, url, data, callback,funparam,funparam2){
var objXMLHttp = this._getInstance();
with(objXMLHttp){
try{
if (url.indexOf("?") > 0){
url = "&randnum=" Math.random();
}
else{
url = "?randnum=" Math.random();
}
open(method, url, true);
setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
send(data);
onreadystatechange = function (){
if (objXMLHttp.readyState == 4 && (objXMLHttp.status == 200 || objXMLHttp.status == 304))
{
callback(objXMLHttp,funparam,funparam2);
}else{
callback(null,funparam,funparam2);
}
}
}
catch(e){
alert(e);
}
}
}
};
/// Cookies操作
var Sams_cookies = {
/* cookies设置函数
@name Cookies名称
@value 值
*/
setCookie : function (name, value)
{
try
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires!=null)
{
var LargeExpDate = new Date ();
LargeExpDate.setTime(LargeExpDate.getTime() (expires*1000*3600*24));
}
document.cookie = name "=" escape (value) ((expires == null) ? "" : ("; expires=" LargeExpDate.toGMTString()));
return true;
}
catch(e)
{
return false;
}
},
/* cookies读取函数
@Name Cookies名称
返回值 Cookies值
*/
getCookie : function (Name)
{
var search = Name "="
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search)
if(offset != -1)
{
offset = search.length
end = document.cookie.indexOf(";", offset)
if(end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
else
{
return;
}
}
}
};

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

AI Hentai Generator
Generate AI Hentai for free.

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 WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
