本文首發(fā)于我的博客
常用工具函數(shù)
Array
js刪除數(shù)組指定item
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
this.splice(i, 1);
break;
}
}
}
js刪除指定index的item
Array.prototype.remove = function (dx) {
if (isNaN(dx) || dx > this.length) {
return false;
}
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) {
this[n++] = this[i]
}
}
this.length -= 1
}
遞歸遍歷數(shù)組成員并輸出
//函數(shù) printArray 使用了遞歸方式疆前,逐一輸出數(shù)組中的每個(gè)成員邻遏,中間以空格隔開(kāi)。
//@arr :應(yīng)是數(shù)組類(lèi)型
function printArray(arr) {
for (var i in arr) {
if (arr[i] instanceof Array) {
printArray(arr[i]);
} else {
document.write(arr[i] + '');
}
}
}
JS插入排序
//此方法排序從小到大
//@arr :應(yīng)是數(shù)組類(lèi)型
function insertionSort(arr) {
//從第二個(gè)元素開(kāi)始
for (var i = i; i < arr.length; i++) {
//取出待比較的元素
var k = arr[i];
//像前找,找到比當(dāng)前元素大的位置
var j;
for (j = i - 1; j >= 0 && k < arr[j]; j--) {
//向后移動(dòng)一位
arr[j + 1] = arr[j];
}
//插入元素
arr[j + 1] = k;
}
}
BOM
判斷瀏覽器
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";
}
}
手機(jī)類(lèi)型判斷
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)),
}
獲取當(dāng)前js的版本
function getjsversion() {
var n = navigator;
var u = n.userAgent;
var apn = n.appName;
var v = n.appVersion;
var ie = v.indexOf('MSIE ');
if (ie > 0) {
apv = parseInt(i = v.substring(ie + 5));
if (apv > 3) {
apv = parseFloat(i);
}
} else {
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 = new Date;
if (tm.setUTCDate) {
javascriptVersion = '1.3';
if (isie && ismac && apv >= 5) javascriptVersion = '1.4';
var pn = 0;
if (pn.toPrecision) {
javascriptVersion = '1.5';
a = new Array;
if (a.forEach) {
javascriptVersion = '1.6';
i = 0;
o = new Object;
tcf = new Function('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;
}
判斷瀏覽器是否支持CSS3屬性
/**
* 判斷是否支持css3
*
* @param {string} style CSS屬性
* @returns
*/
function supportCss3(style) {
var prefix = ['webkit', 'Moz', 'ms', 'o'],
i,
humpString = [],
htmlStyle = document.documentElement.style,
_toHumb = function (string) {
return string.replace(/-(\w)/g, function ($0, $1) {
return $1.toUpperCase();
});
};
for (i in prefix)
humpString.push(_toHumb(prefix[i] + '-' + style));
humpString.push(_toHumb(style));
for (i in humpString)
if (humpString[i] in htmlStyle) return true;
return false;
}
阻止事件冒泡
//@e :事件對(duì)象
function stopPP(e) {
var evt = e || window.event;
//IE用cancelBubble=true來(lái)阻止而FF下需要用stopPropagation方法
evt.stopPropagation ? evt.stopPropagation() : (evt.cancelBubble = true);
}
加入收藏
/**
* 加入收藏
*
* @param {String} sURL
* @param {any} sTitle
*/
function AddFavorite(sURL, sTitle) {
sURL = encodeURI(sURL);
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失敗");
}
}
}
實(shí)現(xiàn)設(shè)為首頁(yè)
/**
* 實(shí)現(xiàn)設(shè)為首頁(yè)
*
* @param {String} url
*/
function SetHome(url) {
if (document.all) {
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage(url);
} else {
alert("設(shè)為首頁(yè)失敗");
}
}
String
JS 替換非法字符主要用在密碼驗(yàn)證上出現(xiàn)的特殊字符
function URLencode(sStr) {
return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
};
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, "");
}
字符串截取方法
function getCharactersLen(charStr, cutCount) {
if (charStr == null || charStr == '') return '';
var totalCount = 0;
var newStr = '';
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;
}
求一個(gè)字符串長(zhǎng)度
//@ str:傳入一個(gè)字符串返回該字符串的長(zhǎng)度
//PS:假設(shè)一個(gè)中文占兩個(gè)字節(jié)断箫,一個(gè)英文占用一個(gè)字節(jié)
function getBytes(str) {
var len = str.length,
//假如全英文字符串則代表字節(jié)長(zhǎng)度與字符串長(zhǎng)度相同
bytes = len,
i = 0;
//循環(huán)遍歷字符串獲取相對(duì)應(yīng)的Unicode 編碼默终,
for (i = 0; i < len; i++) {
if (str[i].charCodeAt() > 255) {
bytes++;
}
}
return bytes;
}
js實(shí)現(xiàn)解析URL參數(shù), 返回一個(gè)對(duì)象
/**
* js實(shí)現(xiàn)解析URL參數(shù)屁擅, 返回一個(gè)對(duì)象
*
* @param {String} url 傳入一個(gè)地址串偿凭,例如"http://www.baidu.com/index.php?key=0&key=1&key=2”
* @returns
*/
function parseQuerystring(url) {
var params = {}, //聲明一個(gè)數(shù)組來(lái)存放返回的對(duì)象
arr = url.split('?'); //將url地址與參數(shù)分割開(kāi)來(lái)
if (arr.length <= 1) { //如果沒(méi)有參數(shù)則代表arr.length長(zhǎng)度<=1
return params;
}
arr = arr[1].split('&'); //解析后面的參數(shù)并返回?cái)?shù)組
//循環(huán)遍歷arr數(shù)組
for (var i = 0, l = arr.length; i < l; i++) {
var a = arr[i].split('=');
params[a[0]] = a[1]; //將分割后的參數(shù)以鍵值對(duì)形式存入params
}
return params;
}
function GetQueryStringRegExp(name, url) {
var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/\+/g, " "));
return "";
}
Date
JS判斷兩個(gè)日期大小 適合 2012 - 09 - 09 與2012 - 9 - 9 兩種格式的對(duì)比
//得到日期值并轉(zhuǎn)化成日期格式,replace(/\-/g, "\/")是根據(jù)驗(yàn)證表達(dá)式把日期轉(zhuǎn)化成長(zhǎng)日期格式派歌,這樣再進(jìn)行判斷就好判斷了
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('開(kāi)始日期要小于結(jié)束日期');
return false;
}
}
}
獲取當(dāng)前時(shí)間
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 + '-' + month + '-' + days + ' ' + hours + ':' + minutes + ':' + seconds;
function add_zero(temp) {
if (temp < 10){
return "0" + temp;
}
return temp;
}
return str;
};
獲取前num天的日期
/**
* 公有方法:獲取前num天的日期
*
* @param {Number} num 自動(dòng)向上取整
* @param {boolean} order true是日期從大到小弯囊,false是從小到大
* @returns MM-dd
*/
function getTodayDate(num, order = false) {
debugger
num = Math.ceil(num)
let arr_Date = []
for (var i = 0; i < num; i++) {
let date = new Date(new Date().getTime() - (i * 24 * 60 * 60 * 1000))
let currMonth = new Date(date).getMonth() + 1
let currDay = new Date(date).getDate()
let result = `${currMonth.toString().length < 2 ? `0${currMonth}` : currMonth}-${currDay.toString().length < 2 ? `0${currDay}` : currDay}`;
if (order) {
arr_Date.push(result);
} else {
arr_Date.unshift(result);
}
}
// console.log(arr_Date);
return arr_Date;
}
console.log(getTodayDate(7));
DOM
增加/移除事件
var EventUtil = {
addHandler:function(element,type,handler){
if(element.addEventListener){//檢測(cè)是否存在DOM2
element.addEventListener(type,handler,false)
}else if(element.attachEvent){//存在ie
element.attachEvent('on'+type,handler)
}else{//DOM0
element['on'+type]=handelr;
}
},
removeHandler:function(element,type,handler){
if(element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if(element.detachEvent){
element.detachEvent('on'+type,handler);
}else{
element['on'+type]=null;
}
}
}
//使用
var btn = document.getElementById('myBtn');
var handler = function(){
console.log('hi')
}
EventUtil.addHandler(btn,'click',handler);
EventUtil.removeHandler(btn,'click',handler);
js實(shí)時(shí)計(jì)算rem,寬度大于1920px時(shí)1rem=100px
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
if (clientWidth >= 1920) {
docEl.style.fontSize = '100px';
} else {
docEl.style.fontSize = 100 * (clientWidth / 1920) + 'px';
}
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
綁定按鈕回車(chē)觸發(fā)單機(jī)事件
$("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();
}
}
按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();
}
};
全選 / 全不選
function selectAll(objSelect) {
if (objSelect.checked == true) {
$("input[name='chkId']").attr("checked", true);
$("input[name='chkAll']").attr("checked", true);
} else if (objSelect.checked == false) {
$("input[name='chkId']").attr("checked", false);
$("input[name='chkAll']").attr("checked", false);
}
}
原生JS獲取鼠標(biāo)XY軸的值
/**
* 原生JS獲取鼠標(biāo)XY軸的值
*
* @param {Object} evt
* @returns
*/
function mousePosition(evt) {
evt = evt || window.event;
//Mozilla
if (evt.pageX || evt.pageY) {
return {
x: evt.pageX,
y: evt.pageY
}
}
//IE
return {
x: evt.clientX + document.body.scrollLeft - document.body.clientLeft,
y: evt.clientY + document.body.scrollTop - document.body.clientTop
}
}
//獲取X軸坐標(biāo)
function getX(evt) {
evt = evt || window.event;
return mousePosition(evt).x;
}
//獲取Y軸坐標(biāo)
function getY(evt) {
evt = evt || window.event;
return mousePosition(evt).y;
}
//外部函數(shù)調(diào)用1
document.getElementById("x").onclick = function (evt) {
alert(getX(evt))
}
//外部函數(shù)調(diào)用2
function showXY(evt) {
evt = evt || window.event;
document.getElementById("n").innerHTML = "" + getX(evt);
}
window.onload = function () {
document.body.onmousemove = showXY;
}
1.在IE中,event對(duì)象是全局的胶果,它被存儲(chǔ)在window.event中匾嘱,對(duì)于Firefox,及其他的瀏覽器來(lái)說(shuō)早抠,這個(gè)事件將被傳遞到任何指向這個(gè)頁(yè)面動(dòng)作的函數(shù)中霎烙。可以通過(guò)傳遞參數(shù)獲取蕊连。
2.document.body.scrollTop是網(wǎng)頁(yè)被卷去的高悬垃,具有 DTD 時(shí)用 document.documentElement.scrollTop 代替 document.body.scrollTop ,否則取不到值咪奖。
3.Firefox和其他的瀏覽器使用event.pageX和event.pageY來(lái)表示鼠標(biāo)相對(duì)于document文檔的位置盗忱。如果你有一個(gè)500500的窗口,并且鼠標(biāo)位于窗口中間羊赵,那么pageX和pageY的值將都是250趟佃。如果你將窗口向下滾動(dòng)500象素扇谣,pageY的值為750。 如此相反的是闲昭,微軟的IE使用event.clientX和event.clientY來(lái)表示鼠標(biāo)相對(duì)于window窗口的位置罐寨,而不是當(dāng)前document文檔。在相同的例子中序矩,如果將鼠標(biāo)放置于500500窗口的中間鸯绿,clientX和clientY值將均為250。如果向下滾動(dòng)頁(yè)面簸淀,clientY將仍為250瓶蝴,因?yàn)樗窍鄬?duì)于window窗口來(lái)測(cè)量,而不是當(dāng)前的document文檔租幕。因此舷手,在鼠標(biāo)位置中,我們應(yīng)該引入document文檔body區(qū)域的scrollLeft和scrollTop屬性劲绪。最后男窟,IE中document文檔實(shí)際并不在(0,0)的位置,在它周?chē)幸粋€(gè)屑指弧(通常有2px)邊框歉眷,document.body.clientLeft和document.body.clientTop包含了這個(gè)邊框的寬度。所有用
evt.clientX + document.body.scrollLeft - document.body.clientLeft //在IE中獲得
JS實(shí)現(xiàn)添加事件兼容函數(shù)
/**
* 公有函數(shù):"事件處理"兼容函數(shù)
*
* @param {Object} evnentObj 需要添加事件的對(duì)象
* @param {String} eventType 添加觸發(fā)事件的類(lèi)型颤枪,如click汗捡,不需要加on
* @param {function} fn 事件函數(shù)
* @param {Boolean} useCapture
*/
function addEvent(evnentObj, eventType, fn, useCapture) {
if (evnentObj.addEventListener) {
evnentObj.addEventListener(eventType, fn, false, useCapture); //DOM 2.0
} else if (evnentObj.attachEvent) {
evnentObj.attachEvent('on' + eventType, fn); //IE5+
} else {
evnentObj['on' + eventType] = fn; //DOM 0.0
}
}
JS獲取某元素以瀏覽器左上角為原點(diǎn)的坐標(biāo)(有問(wèn)題)
/**
* 公有函數(shù):獲取某元素以瀏覽器左上角為原點(diǎn)的坐標(biāo)
*
* @param {Object} obj
* @returns
*/
function getPoint(obj) {
var top = obj.offsetTop; //獲取該元素對(duì)應(yīng)父容器的上邊距
var left = obj.offsetLeft; //對(duì)應(yīng)父容器的上邊距
var objPoint = {};
//判斷是否有父容器,如果存在則累加其邊距
while (obj = obj.offsetParent) {
top += obj.offsetTop;
left += obj.offsetLeft;
}
objPoint.top = top;
objPoint.left = left;
return objPoint;
}
JS獲取鼠標(biāo)X.Y軸坐標(biāo)
function mousePosition(evt) {
evt = evt || window.event;
//Mozilla
if (evt.pageX || evt.pageY) {
return {
x: evt.pageX,
y: evt.pageY
}
}
//IE
return {
x: evt.clientX + document.body.scrollLeft - document.body.clientLeft,
y: evt.clientY + document.body.scrollTop - document.body.clientTop
}
}
Object
js實(shí)現(xiàn)對(duì)象的深Clone
//PS:深度克挛犯佟:所有元素或?qū)傩跃耆珡?fù)制凉唐,與原對(duì)象完全脫離,也就是說(shuō)所有對(duì)于新對(duì)象的修改都不會(huì)反映到原對(duì)象中霍骄。
function cloneObject(o) {
//首先對(duì)傳入的對(duì)象進(jìn)行類(lèi)型判斷,
if (!o || "object" !== typeof o) {
return o;
}
var c = "function" === typeof o.pop ? [] : {};
var p, v;
for (p in o) {
if (o.hasOwnProperty(p)) {
v = o[p];
if (v && 'object' === typeof v) {
c[p] = Ext.ux.clone(v);
} else {
c[p] = v;
}
}
}
return c;
};
Math
JS 生成范圍隨機(jī)整數(shù)
// JS 生成范圍隨機(jī)整數(shù)
/**
* 生成從minNum到maxNum的隨機(jī)整數(shù)
* @param {number} minNum
* @param {number} maxNum
* @param {boolean} [status=true] 生成整數(shù) false生成小數(shù)
* @returns
*/
function randomNum(minNum, maxNum, status = true) {
let result;
console.log(arguments.length);
switch (arguments.length) {
case 1:
result = parseInt(Math.random() * minNum + 1, 10);
break
case 2:
result = parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
break
case 3:
if (status) {
result = parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
break
} else {
result = Math.random() * (maxNum - minNum + 1) + minNum;
break
}
default:
result = 0;
break
}
return result;
}
XML
轉(zhuǎn)成XML對(duì)象
/**
* 轉(zhuǎn)成XML對(duì)象
*
* @param {String} str 一個(gè)xml格式的串
* @returns
*/
function createXml(str) {
if (document.all) {
var xmlDom = new ActiveXObject("Microsoft.XMLDOM")
xmlDom.loadXML(str)
return xmlDom
}
else
return new DOMParser().parseFromString(str, "text/xml")
}
常用例子
格式化數(shù)字串
/**
* 格式化數(shù)字串
* @param {String} str 源字符串
* @param {Number} size 每隔幾個(gè)字符進(jìn)行分割 默認(rèn)3
* @param {String} delimiter delimiter-分割符 默認(rèn)','
*/
function formatText(str, size = 3, delimiter = ',') {
let _str = str.toString(),
regText = '\\d{1,' + size + '}(?=(\\d{' + size + '})+$)',
reg = new RegExp(regText, 'g');
return _str.replace(/^(-?)(\d+)((\.\d+)?)$/,
function ($0, $1, $2, $3) {
return $1 + $2.replace(reg, `$&${delimiter}`) + $3;
})
}
Js身份證驗(yàn)證函數(shù)
// 二代身份證號(hào)碼為 18 位淡溯,其最后一位(第 18 位)的計(jì)算方法為:
// 1读整、 將前面的身份證號(hào)碼 17 位數(shù)分別乘以不同的系數(shù)。從第一位到第十七位的系數(shù)分別 為:7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
// 2咱娶、 將這 17 位數(shù)字和系數(shù)相乘的結(jié)果相加
// 3米间、 用加出來(lái)和除以 11,看余數(shù)是多少?
// 4膘侮、 余數(shù)只可能有 0-1-2-3-4-5-6-7-8-9-10 這 11 個(gè)數(shù)字屈糊。
// 每個(gè)數(shù)字所對(duì)應(yīng)的 最后一位身份證的號(hào)碼為:1-0-X-9-8-7-6-5-4-3-2
// 即,如果余數(shù)是是 2琼了,就會(huì)在身份證的第 18 位數(shù)字上出現(xiàn)羅馬數(shù)字的X逻锐。如果余數(shù)是 10夫晌,身份證的最后一位號(hào)碼就 是 2
// 身份驗(yàn)證函數(shù)
function Authentication() {
const arrXishu = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //聲明系數(shù)數(shù)組
var arrch = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; //聲明最后一位身份證號(hào)碼的數(shù)組
var idcard = document.getElementById("IdCard").value;
var arrIdcard = idcard.split(""); //字符串轉(zhuǎn)化為數(shù)組
var sum = 0;
if (arrIdcard.length != 18) {
return alert("輸入的號(hào)碼有誤");
} else {
for (var index = 0; index < arrXishu.length; index++) {
sum += parseInt(arrXishu[index]) * arrXishu[index];
}
let c = sum % 11;
let code = arrch(c);
if (code == arrIdcard.charAt(17)) {
alert("身份證號(hào)碼正確");
} else {
alert("身份證號(hào)碼錯(cuò)誤");
}
}
}
JS 執(zhí)行計(jì)時(shí)器
timeStart = new Date().getTime();
timesEnd = new Date().getTime();
document.getElementById("time").innerHTML = timesEnd - timeStart;
JS寫(xiě)入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;
};
JS 讀Cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (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 decodeURIComponent(c.substring(nameEQ.length, c.length))
}
}
return null
}
原生Ajax 請(qǐng)求
function jsAjax(args) {
var self = this;
this.options = {
type: 'GET',
async: true,
contentType: 'application/x-www-form-urlencoded',
url: 'about:blank',
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('您的瀏覽器不支持AJAX');
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() == 'GET') {
xmlHttp.open(self.options.type, self.options.url + (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? '&' : '?') + self.options.data)), self.options.async);
} else {
xmlHttp.open(self.options.type, self.options.url, self.options.async);
xmlHttp.setRequestHeader('Content-Length', 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.responseText);
xmlHttp = null;
} else {
if (typeof self.options.error == 'function') self.options.error('Server Status: ' + xmlHttp.status);
}
}
};
xmlHttp.send(self.options.type.toUpperCase() == 'POST' ? self.options.data.toString() : null);
};
this.send();
};
JS 加載到頂部LoadJS
function loadJS(url, fn) {
var ss = document.getElementsByName('script'),
loaded = false;
for (var i = 0, len = ss.length; i < len; i++) {
if (ss[i].src && ss[i].getAttribute('src') == url) {
loaded = true;
break;
}
}
if (loaded) {
if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
return false;
}
var s = document.createElement('script'),
b = false;
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', url);
s.onload = s.onreadystatechange = function () {
if (!b && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
b = true;
if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
};
function bind(objId, eventType, callBack) { //適用于任何瀏覽器的綁定
var obj = document.getElementById(objId);
if (obj.addEventListener) {
obj.addEventListener(eventType, callBack, false);
} else if (window.attachEvent) {
obj.attachEvent('on' + eventType, callBack);
} else {
obj['on' + 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);
}
清空 LoadJS 加載到頂部的js引用
function ClearHeadJs(src) {
var js = document.getElementsByTagName('head')[0].children;
var obj = null;
for (var i = 0; i < js.length; i++) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName('head')[0].removeChild(obj);
};
js 動(dòng)態(tài)移除 head 里的 js 引用
function ClearHeadJs(src) {
var js = document.getElementsByTagName('head')[0].children;
var obj = null;
for (var i = 0; i < js.length; i++) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName('head')[0].removeChild(obj);
};
整個(gè)URL 點(diǎn)擊事件 加在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();
};
獲取地址欄某個(gè)參數(shù)的字段
/**
* 獲取地址欄某個(gè)參數(shù)的字段
*
* @param {any} name
* @returns
*/
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}