El método JS que a menudo se usa, tenga en cuenta que hoy para una consulta futura
/* Juicio de tipo de teléfono*/
La copia del código es la siguiente:
var browserInfo = {
UserAgent: navigator.useragent.tolowercase ()
Isandroid: boolean (navigator.useragent.match (/android/ig)),
Isiphone: Boolean (Navigator.Useragent.Match (/iPhone | iPod/IG)),
ISIPAD: boolean (navigator.useragent.match (/ipad/ig)),
isweixin: boolean (navigator.useragent.match (/micromessenger/ig)),
}
/ * Devuelve la longitud de la cadena, el recuento de hombres es 2 */
La copia del código es la siguiente:
función strlength (str) {
var a = 0;
para (var i = 0; i <str.length; i ++) {
if (str.charcodeat (i)> 255)
a += 2; // aumentar por 2 como se esperaba
demás
a ++;
}
regresar a;
}
Obtener parámetros en URL
La copia del código es la siguiente:
function getQueryRtringegExp (nombre, url) {
var reg = new Regexp ("(^| //? | &)" + nombre + "= ([^&]*) (// s | & | $)", "i");
if (reg.test (url)) return DecodeUriComponent (regexp. $ 2.replace (//+/g, "")); devolver "";
}
/* El evento de enlace JS es adecuado para la unión de elementos de cualquier navegador*/
La copia del código es la siguiente:
function EventBind (OBJ, EventType, Callback) {
if (obj.addeventListener) {
obj.addeventListener (eventtype, devolución de llamada, falso);
}
else if (window.attachevent) {
obj.attachevent ('on' + eventtype, devolución de llamada);
}
demás {
obj ['on' + eventType] = llamado;
}
};
EventBind (documento, 'Click', BodyClick);
/* Obtenga la versión JS de navegador actual*/
La copia del código es la siguiente:
función getJSVERSION () {
var n = navegador;
var u = n.useragent;
var apn = n.appname;
var v = n.appversion;
var ie = v.indexof ('msie');
if (es decir> 0) {
apv = parseInt (i = v.substring (es decir + 5));
if (apv> 3) {
apv = parsefloat (i);
}
} demás {
apv = parsefloat (v);
}
var isie = (apn == 'Microsoft Internet Explorer');
var isMac = (U.IndexOf ('Mac')> = 0);
var javaScriptVersion = "1.0";
if (string && string.prototype) {
javaScriptVersion = '1.1';
if (javascriptVersion.match) {
javaScriptVersion = '1.2';
var tm = nueva fecha;
if (tM.SetUtcDate) {
javaScriptVersion = '1.3';
if (isie && ismac && apv> = 5) javaScriptVersion = '1.4';
var pn = 0;
if (pn.toprecision) {
javaScriptVersion = '1.5';
a = nueva matriz;
if (A.ForEach) {
javaScriptVersion = '1.6';
i = 0;
o = nuevo objeto;
tcf = nueva función ('o', 'var e, i = 0; try {i = new iterator (o)} catch (e) {} return i');
i = tcf (o);
if (i && i.next) {
javaScriptVersion = '1.7';
}
}
}
}
}
}
return javaScriptVersion;
}
/* Obtenga el objeto objeto del evento de clic actual*/
La copia del código es la siguiente:
función getEvent () {
if (document.all) {
Ventana de retorno.event; // Si es, es decir
}
func = getEvent.caller;
while (func! = null) {
var arg0 = func.arguments [0];
if (arg0) {
if ((arg0.constructor == evento || arg0.constructor == mouseevent)
|| (typeof (arg0) == "objeto" && arg0.preventDefault && arg0.stoppropagation)) {
regresar arg0;
}
}
func = func.caller;
}
regresar nulo;
};
/* Método de intercepción de cadena*/
La copia del código es la siguiente:
getCharacterSlen: function (charstr, cutcount) {
if (charstr == null || charstr == '') return '';
var totalCount = 0;
var newStr = '';
para (var i = 0; i <charstr.length; i ++) {
var c = charstr.charcodeat (i);
if (c <255 && c> 0) {
TotalCount ++;
} demás {
TotalCount += 2;
}
if (totalCount> = cutcount) {
Newstr += charstr.charat (i);
romper;
}
demás {
Newstr += charstr.charat (i);
}
}
Return Newstr;
}
/* JS aparece por la nueva pantalla completa de la ventana*/
La copia del código es la siguiente:
var tmp = window.open ("Acerca de: en blanco", "", "FullScreen = 1")
tmp.moveto (0, 0);
tmp.resizeto (Screen.Width + 20, Screen.Height);
tmp.focus ();
tmp.location.href = 'http://www.che168.com/pinggu/eva_' + msgresult.message [0] + '.html';
var config_ = "left = 0, top = 0, width =" + (window.screen.width) + ", tight =" + (window.screen.height);
Window.open ('http://www.che168.com/pinggu/eva_' + msgresult.message [0] + '.html', "winhanle", config_);
// simular la envío del formulario para abrir una nueva página
var f = document.createElement ("formulario");
F.SetAttribute ('Action', 'http://www.che168.com/pinggu/eva_' + msgresult.message [0] + '.html');
f.target = '_blank';
document.body.appendChild (f);
F.Submit ();
/* Seleccionar todo/sin selección*/
La copia del código es la siguiente:
función selectAll (objelect) {
if (objelect.checked == true) {
$ ("entrada [name = 'chkid']"). attr ("verificado", true);
$ ("entrada [name = 'chkall']"). attr ("verificado", true);
}
else if (objSelect.Checked == falso) {
$ ("input [name = 'chkid']"). attr ("verificado", falso);
$ ("entrada [name = 'chkall']"). attr ("verificado", falso);
}
}
/* JS JUEZ BROWSER*/
La copia del código es la siguiente:
Determinar si es un navegador IE
if (document.all) {
alerta ("es decir, navegador");
}demás{
alerta ("navegador no II");
}
if (!! window.activexObject) {
alerta ("es decir, navegador");
}demás{
alerta ("navegador no II");
}
Que es es decir
var isie = !! window.activexObject;
var isie6 = isie &&! window.xmlhttprequest;
var isie8 = isie && !! document.documentMode;
var isie7 = isie &&! isie6 &&! isie8;
if (isie) {
if (isie6) {
alerta ("ie6");
} else if (isie8) {
alerta ("IE8");
} else if (isie7) {
alerta ("IE7");
}
}
/* Navegador de juicio*/
La copia del código es la siguiente:
función getos () {
if (navigator.useragent.indexof ("msie 8.0")> 0) {
regresar "msie8";
}
else if (navigator.useragent.indexof ("msie 6.0")> 0) {
regresar "msie6";
}
else if (navigator.useragent.indexof ("msie 7.0")> 0) {
regresar "msie7";
}
else if (isfirefox = navigator.useragent.indexof ("firefox")> 0) {
regresar "Firefox";
}
if (navigator.useragent.indexof ("chrome")> 0) {
regresar "Chrome";
}
demás {
regresar "otro";
}
}
/* JS determina que el tamaño de dos fechas es adecuado para 2012-09-09 y 2012-9-9*/
La copia del código es la siguiente:
// Obtenga el valor de la fecha y conviértalo en el formato de fecha. Reemplazar (//-/g, "//") convierte la fecha en un formato de fecha largo basado en la expresión de verificación, para que sea fácil hacer un juicio.
function validateate () {
var begindate = $ ("#t_datesteart"). val ();
var endDate = $ ("#t_dateend"). val ();
if (begindate.length> 0 && enddate.length> 0) {
var sdate = nueva fecha (begindate.replace (//-/g, "//"));
var edate = nueva fecha (enddate.replace (//-/g, "//"));
if (sdate> edate) {
alerta ('la fecha de inicio debe ser menor que la fecha de finalización');
devolver falso;
}
}
}
/* Eliminar el evento*/
La copia del código es la siguiente:
this.moveBind = function (objid, eventType, llamado) {
var obj = document.getElementById (objid);
if (obj.removeEventListener) {
obj.removeEventListener (eventtype, devolución de llamada, falso);
}
else if (window.detachevent) {
obj.detachevent ('on' + eventtype, llamado);
}
demás {
obj ['on' + eventtype] = null;
}
}
/* Ingrese para enviar*/
La copia del código es la siguiente:
$ ("id"). onKeyPress = function (evento) {
evento = (evento)? Evento: ((Window.event)? Window.event: "")
KeyCode = Event.KeyCode? Event.KeyCode: (event.whhh?
if (keyCode == 13) {
$ ("SubtLogin"). OnClick ();
}
}
/* JS Temperador de ejecución*/
La copia del código es la siguiente:
timStart = new Date (). GetTime ();
Timesend = new Date (). GetTime ();
document.getElementById ("Tiempo"). Innerhtml = Timesend - TimStart;
/ * JS escribe cookies */
La copia del código es la siguiente:
función setcookie (nombre, valor, expiración, ruta, dominio) {
if (! expires) expiras = -1;
if (! Path) ruta = "/";
var d = "" + nombre + "=" + valor;
var e;
if (expires <0) {
e = "";
}
else if (expires == 0) {
var f = nueva fecha (1970, 1, 1);
e = "; expires =" + F.ToutCString ();
}
demás {
var ahora = nueva fecha ();
var f = nueva fecha (ahora.gettime () + expirada * 1000);
e = "; expires =" + F.ToutCString ();
}
var dm;
if (! dominio) {
dm = "";
}
demás {
dm = "; dominio =" + dominio;
}
document.cookie = name + "=" + valor + "; path =" + ruta + e + dm;
};
/ * JS lee cookies */
La copia del código es la siguiente:
función readCookie (nombre) {
var nameeq = name + "=";
var ca = document.cookie.split (';');
para (var i = 0; i <ca.length; i ++) {
var c = ca [i];
while (c.charat (0) == '') c = C.Substring (1, C.Length);
if (c.indexof (nameeq) == 0) {
return DecodeuricOponent (C.Substring (Nameeq.Length, C.Length))
}
} return null
}
/* Solicitud AJAX*/
La copia del código es la siguiente:
C.AJAX = function (args) {
var self = this;
this.options = {
Tipo: 'Get',
Async: verdadero,
ContentType: 'Application/x-www-form-urlencoded',
URL: 'Acerca de: en blanco',
Datos: NULL,
éxito: {},
error: {}
};
this.getxmlhttp = function () {
var xmlhttp;
intentar {
xmlhttp = new xmlhttprequest ();
}
Catch (e) {
intentar {
xmlhttp = new ActiveXObject ("msxml2.xmlhttp");
}
Catch (e) {
xmlhttp = new ActiveXObject ("Microsoft.xmlhttp");
}
}
if (! xmlhttp) {
alerta ('Su navegador no admite AJAX');
devolver falso;
}
return xmlhttp;
};
this.send = function () {
C.Each (self.options, function (key, val) {
self.options [key] = (args [key] == nulo)? Val: Args [clave];
});
var xmlhttp = new self.getxmlhttp ();
if (self.options.type.touppercase () == 'get') {
xmlhttp.open (self.options.type, self.options.url + (self.options.data == null? "": ((/= ?font>$/.test(Self.options.url)? '&': '?') + self.options.data)), self.options.async);
}
demás {
xmlhttp.open (self.options.type, self.options.url, self.options.async);
xmlhttp.setRequestHeader ('content-longitud', self.options.data.length);
}
xmlhttp.setRequestHeader ('content-type', self.options.contentType);
xmlhttp.onreadyStateChange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 || xmlhttp.status == 0) {
if (typeof self.options.success == 'function') self.options.success (xmlhttp.esponsetext);
xmlhttp = null;
}
demás {
if (typeof self.options.error == 'function') self.options.error ('estado del servidor:' + xmlhttp.status);
}
}
};
xmlhttp.send (self.options.type.touppercase () == 'post'? self.options.data.ToString (): null);
};
this.send ();
};
/* JS StringBuilder Uso*/
La copia del código es la siguiente:
función stringBuilder () {
this.strings = nueva matriz;
};
StringBuilder.prototype.append = function (str) {
this.strings.push (str);
};
StringBuilder.Prototype.ToString = function () {
devolver esto.strings.Join ('');
};
/ * JS se carga hasta la carga superior */
La copia del código es la siguiente:
function loadjs (url, fn) {
var ss = document.getElementsByName ('script'),
cargado = falso;
para (var i = 0, len = ss.length; i <len; i ++) {
if (ss [i] .src && ss [i] .getAttribute ('src') == url) {
cargado = verdadero;
romper;
}
}
if (cargado) {
if (fn && typeof fn! = 'undefined' && fn instanceOf function) fn ();
devolver falso;
}
var s = document.createElement ('script'),
b = falso;
s.setAttribute ('type', 'text/javaScript');
s.setAttribute ('src', url);
s.onload = s.onreadyStateChange = function () {
if (! b && (! this.readyState || this.readyState == 'cargado' || this.readyState == 'completo')) {
b = verdadero;
if (fn && typeof fn! = 'undefined' && fn instanceOf function) fn ();
}
};
document.getElementsByTagName ('Head') [0] .AppendChild (s);
},
Bind: function (objid, eventType, llamado) {// vinculante para cualquier navegador
var obj = document.getElementById (objid);
if (obj.addeventListener) {
obj.addeventListener (eventtype, devolución de llamada, falso);
}
else if (window.attachevent) {
obj.attachevent ('on' + eventtype, devolución de llamada);
}
demás {
obj ['on' + eventType] = llamado;
}
}
función jsload (args) {
s = document.createElement ("script");
s.setAttribute ("type", "text/javaScript");
S.SetAttribute ("Src", args.url);
s.onload = s.onreadyStateChange = function () {
if (! S. S.ReadyState || s.readyState == "Cargado" || S.ReadyState == "Complete") {
if (typeof args.callback == "función") args.callback (this, args);
s.onload = s.onreadyStateChange = null;
intentar {
s.parentnode && s.parentnode.removechild (s);
} catch (e) {}
}
};
document.getElementsBytagName ("Head") [0] .AppendChild (s);
}
/* Borrar la referencia JS cargada en la parte superior de Loadjs*/
La copia del código es la siguiente:
función ClearHeadjs (SRC) {
var js = document.getElementsByTagName ('Head') [0] .children;
var obj = null;
para (var i = 0; i <js.length; i ++) {
if (js [i] .tagname.tolowercase () == "script" && js [i] .attributes ['src']. valor.indexof (src)> 0) {
obj = js [i];
}
}
document.getElementsByTagName ('Head') [0] .RemoVechild (obj);
};
/* JS reemplaza los caracteres ilegales principalmente por caracteres especiales que aparecen en la verificación de contraseña*/
La copia del código es la siguiente:
función urlencode (sstr) {
Return Escape (SSTR) .replace (//+/g, '%2b'). Reemplazar (// "/g, '%22'). Reemplazar (// '/g,'%27 '). Reemplazar (//// g,'%2f ');
};
/* Presione Ctrl + Ingrese para enviar el formulario directamente*/
La copia del código es la siguiente:
document.body.onkeydown = function (evt) {
EVT = EVT? EVT: (Window.event? Window.event: NULL);
if (13 == evt.keycode && evt.ctrlkey) {
evt.returnValue = false;
evt.cancel = true;
Postdata ();
}
};
/* Obtenga la hora actual*/
La copia del código es la siguiente:
función getCurrentDate () {
var d = nueva fecha ();
var y = d.getyear ()+1900;
mes = add_zero (d.getMonth () + 1),
días = add_zero (d.getDate ()),
horas = add_zero (d.gethours ());
minutos = add_zero (d.getmines ()),
segundos = add_zero (d.getSeconds ());
var str = y + '-' + mes + '-' + días + '' + horas + ':' + minutos + ':' + segundos;
regresar str;
};
función add_zero (temp) {
if (temp <10) return "0" + temp;
el otro otro temperatura de retorno;
}
/ * Método JS para eliminar espacios: */
La copia del código es la siguiente:
String.prototype.trim = function ()
{return this.replace (/(^/s*) | (/s*$)/g, ""); }
String.prototype.ltrim = function ()
{return this.replace (/(^/s*)/g, "");}
String.prototype.rtrim = function ()
{return this.replace (/(/s*$)/g, "");}
/* JS elimina dinámicamente la referencia JS en la cabeza*/
La copia del código es la siguiente:
this.clearHeadjs = function (src) {
var js = document.getElementsByTagName ('Head') [0] .children;
var obj = null;
para (var i = 0; i <js.length; i ++) {
if (js [i] .tagname.tolowercase () == "script" && js [i] .attributes ['src']. valor.indexof (src)> 0) {
obj = js [i];
}
}
document.getElementsByTagName ('Head') [0] .RemoVechild (obj);
};
/* Todo el evento de clic UL se agrega al OnClick en UL*/
La copia del código es la siguiente:
función createFrom (url, params) {
var f = document.createElement ("formulario");
F.SetAttribute ("Acción", URL);
para (var i = 0; i <params.length; i ++) {
var input = document.createElement ("entrada");
input.SetAttribute ("type", "oculto");
input.SetAttribute ("Nombre", Params [i] .ParamName);
input.SetAttribute ("Valor", Params [i] .ParamValue);
F.AppendChild (entrada);
}
f.target = "_blank";
document.body.appendChild (f);
F.Submit ();
};
/* Determinar qué versión JS está usando el navegador*/
La copia del código es la siguiente:
<script language = "javaScript">
var jsVersion = 1.0;
</script>
<script language = "javaScript1.1">
JSVersion = 1.1;
</script>
<script language = "javaScript1.2">
JSVersion = 1.2;
</script>
<script language = "javaScript1.3">
JSVersion = 1.3;
</script>
<script language = "javaScript1.4">
JSVersion = 1.4;
</script>
<script language = "javaScript1.5">
JSVERSION = 1.5;
</script>
<script language = "javaScript1.6">
JSVERSION = 1.6;
</script>
<script language = "javaScript1.7">
JSVersion = 1.7;
</script>
<script language = "javaScript1.8">
JSVersion = 1.8;
</script>
<script language = "javaScript1.9">
JSVersion = 1.9;
</script>
<script language = "javaScript2.0">
JSVersion = 2.0;
</script>
alerta (jsversion);
Lo anterior es todo el contenido de este artículo. Espero que sea útil para todos y no será en vano durante tanto tiempo, jaja.