Home Web Front-end JS Tutorial Summary of common JavaScript methods

Summary of common JavaScript methods

Feb 04, 2017 pm 05:01 PM
javascript

经常使用的 JS 方法,今天记下,以便以后查询

/* 手机类型判断 */
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)),
}
Copy after login

/* 返回字符串长度,汉子计数为2 */

function strLength(str) {
var a = 0;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255)
a += 2;//按照预期计数增加2
else
a++;
}
return a;
}
Copy after login

获取url中的参数

function GetQueryStringRegExp(name,url) {
var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/\+/g, " ")); return "";
}  
Copy after login

/* js 绑定事件 适用于任何浏览器的元素绑定 */

function eventBind(obj, eventType, callBack) {
if (obj.addEventListener) {
obj.addEventListener(eventType, callBack, false);
}
else if (window.attachEvent) {
obj.attachEvent(&#39;on&#39; + eventType, callBack);
}
else {
obj[&#39;on&#39; + eventType] = callBack;
}
};
eventBind(document, &#39;click&#39;, bodyClick);  
Copy after login

/* 获得当前浏览器JS的版本 */

function getjsversion(){
var n = navigator;
var u = n.userAgent;
var apn = n.appName;
var v = n.appVersion;
var ie = v.indexOf(&#39;MSIE &#39;);
if (ie > 0){
apv = parseInt(i = v.substring(ie + 5));
if (apv > 3) {
apv = parseFloat(i);
}
} else {
apv = parseFloat(v);
}
var isie = (apn == &#39;Microsoft Internet Explorer&#39;);
var ismac = (u.indexOf(&#39;Mac&#39;) >= 0);
var javascriptVersion = "1.0";
if (String && String.prototype) {
javascriptVersion = &#39;1.1&#39;;
if (javascriptVersion.match) {
javascriptVersion = &#39;1.2&#39;;
var tm = new Date;
if (tm.setUTCDate) {
javascriptVersion = &#39;1.3&#39;;
if (isie && ismac && apv >= 5) javascriptVersion = &#39;1.4&#39;;
var pn = 0;
if (pn.toPrecision) {
javascriptVersion = &#39;1.5&#39;;
a = new Array;
if (a.forEach) {
javascriptVersion = &#39;1.6&#39;;
i = 0;
o = new Object;
tcf = new Function(&#39;o&#39;, &#39;var e,i=0;try{i=new Iterator(o)}catch(e){}return i&#39;);
i = tcf(o);
if (i && i.next) {
javascriptVersion = &#39;1.7&#39;;
}
}
}
}
}
}
return javascriptVersion;
}  
Copy after login

/* 获取当前点击事件的Object对象 */

function getEvent() {
if (document.all) {
return window.event; //如果是ie
}
func = getEvent.caller;
while (func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if ((arg0.constructor == Event || arg0.constructor == MouseEvent)
|| (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func = func.caller;
}
return null;
};  
Copy after login

/* 字符串截取方法 */

getCharactersLen: function (charStr, cutCount) {
if (charStr == null || charStr == &#39;&#39;) return &#39;&#39;;
var totalCount = 0;
var newStr = &#39;&#39;;
for (var i = 0; i < charStr.length; i++) {
var c = charStr.charCodeAt(i);
if (c < 255 && c > 0) {
totalCount++;
} else {
totalCount += 2;
}
if (totalCount >= cutCount) {
newStr += charStr.charAt(i);
break;
}
else {
newStr += charStr.charAt(i);
}
}
return newStr;
}  
Copy after login

/* JS 弹出新窗口全屏 */

var tmp = window.open("about:blank", "", "fullscreen=1")
tmp.moveTo(0, 0);
tmp.resizeTo(screen.width + 20, screen.height);
tmp.focus();
tmp.location.href = &#39;http://www.che168.com/pinggu/eva_&#39; + msgResult.message[0] + &#39;.html&#39;;

var config_ = "left=0,top=0,width=" + (window.screen.Width) + ",height=" + (window.screen.Height);
window.open(&#39;http://www.che168.com/pinggu/eva_&#39; + msgResult.message[0] + &#39;.html&#39;, "winHanle", config_);
//模拟form提交打开新页面
var f = document.createElement("form");
f.setAttribute(&#39;action&#39;, &#39;http://www.che168.com/pinggu/eva_&#39; + msgResult.message[0] + &#39;.html&#39;);
f.target = &#39;_blank&#39;;
document.body.appendChild(f);
f.submit();  
Copy after login

/* 全选/全不选 */

function selectAll(objSelect) {
if (objSelect.checked == true) {
$("input[name=&#39;chkId&#39;]").attr("checked", true);
$("input[name=&#39;chkAll&#39;]").attr("checked", true);
}
else if (objSelect.checked == false) {
$("input[name=&#39;chkId&#39;]").attr("checked", false);
$("input[name=&#39;chkAll&#39;]").attr("checked", false);
}
}
Copy after login

/* js 判断浏览器 */

判断是否是 IE 浏览器
if (document.all){
alert(”IE浏览器”);
}else{
alert(”非IE浏览器”);
}
if (!!window.ActiveXObject){
alert(”IE浏览器”);
}else{
alert(”非IE浏览器”);
}
判断是IE几
var isIE=!!window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var isIE8=isIE&&!!document.documentMode;
var isIE7=isIE&&!isIE6&&!isIE8;
if (isIE){
if (isIE6){
alert(”ie6″);
}else if (isIE8){
alert(”ie8″);
}else if (isIE7){
alert(”ie7″);
}
}  
Copy after login

/* 判断浏览器 */

function getOs() {
if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
return "MSIE8";
}
else if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
return "MSIE6";
}
else if (navigator.userAgent.indexOf("MSIE 7.0") > 0) {
return "MSIE7";
}
else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
return "Firefox";
}
if (navigator.userAgent.indexOf("Chrome") > 0) {
return "Chrome";
}
else {
return "Other";
}
}  
Copy after login

/* JS判断两个日期大小 适合 2012-09-09 与2012-9-9 两种格式的对比 */

//得到日期值并转化成日期格式,replace(/\-/g, "\/")是根据验证表达式把日期转化成长日期格式,这样再进行判断就好判断了
function ValidateDate() {
var beginDate = $("#t_datestart").val();
var endDate = $("#t_dateend").val();
if (beginDate.length > 0 && endDate.length>0) {
var sDate = new Date(beginDate.replace(/\-/g, "\/"));
var eDate= new Date(endDate.replace(/\-/g, "\/"));
if (sDate > eDate) {
alert(&#39;开始日期要小于结束日期&#39;);
return false;
}
}
}  
Copy after login

/* 移除事件 */

this.moveBind = function (objId, eventType, callBack) {
var obj = document.getElementById(objId);
if (obj.removeEventListener) {
obj.removeEventListener(eventType, callBack, false);
}
else if (window.detachEvent) {
obj.detachEvent(&#39;on&#39; + eventType, callBack);
}
else {
obj[&#39;on&#39; + eventType] = null;
}
}  
Copy after login

/* 回车提交 */

$("id").onkeypress = function (event) {
event = (event) ? event : ((window.event) ? window.event : "")
keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode);
if (keyCode == 13) {
$("SubmitLogin").onclick();
}
}  
Copy after login

/* JS 执行计时器 */

timeStart = new Date().getTime();
timesEnd = new Date().getTime();
document.getElementById("time").innerHTML = timesEnd - timeStart;
Copy after login

/* JS 写Cookie */

function setCookie(name, value, expires, path, domain) {
if (!expires) expires = -1;
if (!path) path = "/";
var d = "" + name + "=" + value;
var e;
if (expires < 0) {
e = "";
}
else if (expires == 0) {
var f = new Date(1970, 1, 1);
e = ";expires=" + f.toUTCString();
}
else {
var now = new Date();
var f = new Date(now.getTime() + expires * 1000);
e = ";expires=" + f.toUTCString();
}
var dm;
if (!domain) {
dm = "";
}
else {
dm = ";domain=" + domain;
}
document.cookie = name + "=" + value + ";path=" + path + e + dm;
};  
Copy after login

/* JS 读Cookie */

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(&#39;;&#39;);
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == &#39; &#39;) c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) {
return decodeURIComponent(c.substring(nameEQ.length, c.length))
}
} return null
}  
Copy after login

/* Ajax 请求 */

C.ajax = function (args) {
var self = this;
this.options = {
type: &#39;GET&#39;,
async: true,
contentType: &#39;application/x-www-form-urlencoded&#39;,
url: &#39;about:blank&#39;,
data: null,
success: {},
error: {}
};
this.getXmlHttp = function () {
var xmlHttp;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlhttp) {
alert(&#39;您的浏览器不支持AJAX&#39;);
return false;
}
return xmlhttp;
};
this.send = function () {
C.each(self.options, function (key, val) {
self.options[key] = (args[key] == null) ? val : args[key];
});

var xmlHttp = new self.getXmlHttp();
if (self.options.type.toUpperCase() == &#39;GET&#39;) {
xmlHttp.open(self.options.type, self.options.url + (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? &#39;&&#39; : &#39;?&#39;) + self.options.data)), self.options.async);
}
else {
xmlHttp.open(self.options.type, self.options.url, self.options.async);
xmlHttp.setRequestHeader(&#39;Content-Length&#39;, self.options.data.length);
}
xmlHttp.setRequestHeader(&#39;Content-Type&#39;, self.options.contentType);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200 || xmlHttp.status == 0) {
if (typeof self.options.success == &#39;function&#39;) self.options.success(xmlHttp.responseText);
xmlHttp = null;
}
else {
if (typeof self.options.error == &#39;function&#39;) self.options.error(&#39;Server Status: &#39; + xmlHttp.status);
}
}
};

xmlHttp.send(self.options.type.toUpperCase() == &#39;POST&#39; ? self.options.data.toString() : null);
};
this.send();
};  
Copy after login

/* JS StringBuilder 用法 */

function StringBuilder() {
this.strings = new Array;
};
StringBuilder.prototype.append = function (str) {
this.strings.push(str);
};
StringBuilder.prototype.toString = function () {
return this.strings.join(&#39;&#39;);
};  
Copy after login

/* JS 加载到顶部LoadJS */

function loadJS (url, fn) {
var ss = document.getElementsByName(&#39;script&#39;),
loaded = false;
for (var i = 0, len = ss.length; i < len; i++) {
if (ss[i].src && ss[i].getAttribute(&#39;src&#39;) == url) {
loaded = true;
break;
}
}
if (loaded) {
if (fn && typeof fn != &#39;undefined&#39; && fn instanceof Function) fn();
return false;
}
var s = document.createElement(&#39;script&#39;),
b = false;
s.setAttribute(&#39;type&#39;, &#39;text/javascript&#39;);
s.setAttribute(&#39;src&#39;, url);
s.onload = s.onreadystatechange = function () {
if (!b && (!this.readyState || this.readyState == &#39;loaded&#39; || this.readyState == &#39;complete&#39;)) {
b = true;
if (fn && typeof fn != &#39;undefined&#39; && fn instanceof Function) fn();
}
};
document.getElementsByTagName(&#39;head&#39;)[0].appendChild(s);
},
bind: function (objId, eventType, callBack) { //适用于任何浏览器的绑定
var obj = document.getElementById(objId);
if (obj.addEventListener) {
obj.addEventListener(eventType, callBack, false);
}
else if (window.attachEvent) {
obj.attachEvent(&#39;on&#39; + eventType, callBack);
}
else {
obj[&#39;on&#39; + eventType] = callBack;
}
}

function JSLoad (args) {
s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", args.url);
s.onload = s.onreadystatechange = function () {
if (!s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
if (typeof args.callback == "function") args.callback(this, args);
s.onload = s.onreadystatechange = null;
try {
s.parentNode && s.parentNode.removeChild(s);
} catch (e) { }
}
};
document.getElementsByTagName("head")[0].appendChild(s);
}  
Copy after login

/* 清空 LoadJS 加载到顶部的js引用 */

function ClearHeadJs (src) {
var js = document.getElementsByTagName(&#39;head&#39;)[0].children;
var obj = null;
for (var i = 0; i < js.length; i++) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes[&#39;src&#39;].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName(&#39;head&#39;)[0].removeChild(obj);
};  
Copy after login

/* JS 替换非法字符主要用在密码验证上出现的特殊字符 */

function URLencode(sStr) {
return escape(sStr).replace(/\+/g, &#39;%2B&#39;).replace(/\"/g, &#39;%22&#39;).replace(/\&#39;/g, &#39;%27&#39;).replace(/\//g, &#39;%2F&#39;);
};  
Copy after login

/* 按Ctrl + Entert 直接提交表单 */

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();
}
};  
Copy after login

/* 获取当前时间 */

function GetCurrentDate() {
var d = new Date();
var y = d.getYear()+1900;
month = add_zero(d.getMonth() + 1),
days = add_zero(d.getDate()),
hours = add_zero(d.getHours());
minutes = add_zero(d.getMinutes()),
seconds = add_zero(d.getSeconds());
var str = y + &#39;-&#39; + month + &#39;-&#39; + days + &#39; &#39; + hours + &#39;:&#39; + minutes + &#39;:&#39; + seconds;
return str;
};
function add_zero(temp) {
if (temp < 10) return "0" + temp;
else return temp;
}  
Copy after login

/* Js 去掉空格方法: */

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, "");}  
Copy after login

/* js 动态移除 head 里的 js 引用 */

this.ClearHeadJs = function (src) {
var js = document.getElementsByTagName(&#39;head&#39;)[0].children;
var obj = null;
for (var i = 0; i < js.length; i++) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes[&#39;src&#39;].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName(&#39;head&#39;)[0].removeChild(obj);
};  
Copy after login

/* 整个UL 点击事件 加在UL里的onclick里 */

function CreateFrom(url, params) {
var f = document.createElement("form");
f.setAttribute("action", url);
for (var i = 0; i < params.length; i++) {
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", params[i].paramName);
input.setAttribute("value", params[i].paramValue);
f.appendChild(input);
}
f.target = "_blank";
document.body.appendChild(f);
f.submit();
};  
Copy after login

/* 判断浏览器使用的是哪个 JS 版本 */

<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>
alert(jsversion);
Copy after login

更多JavaScript 常用方法总结相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

See all articles