javascript常用方法
阿新 • • 發佈:2018-12-19
1.Json物件日期處理:
(Json日期格式:Date(1316756746000)/',轉換後格式:yyyy-MM-dd)
function ChangeDateFormat(jsondate) { jsondate = jsondate.replace("/Date(", "").replace(")/", ""); if (jsondate.indexOf("+") > 0) { jsondate = jsondate.substring(0, jsondate.indexOf("+")); } else if (jsondate.indexOf("-") > 0) { jsondate = jsondate.substring(0, jsondate.indexOf("-")); } var date = new Date(parseInt(jsondate, 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); if (date.getFullYear() != 1900) return date.getFullYear() + "-" + month + "-" + currentDate; else return ""; }
2.獲取URL位址列上引數
function GetArgs() { var args = new Object(); var query = location.search.substring(1); // Get query string var pairs = query.split("&"); // Break at ampersand for (var i = 0; i < pairs.length; i++) { var pos = pairs[i].indexOf('='); // Look for "name=value" if (pos == -1) continue; // If not found, skip var argname = pairs[i].substring(0, pos); // Extract the name var value = pairs[i].substring(pos + 1); // Extract the value value = decodeURIComponent(value); // Decode it, if needed args[argname] = value; // Store as a property } return args; // Return the object }
3.是否是INT型別
function KeyIsIntNumber(KeyCode, key) {//如果輸入的字元是在0-9之間,或者是backspace、DEL鍵 if (KeyCode == 13) { event.keyCode = 9; return true; } if (KeyCode == 9) { event.keyCode = 9; return true; } if (((KeyCode > 47) && (KeyCode < 58)) || ((KeyCode > 95) && (KeyCode < 106)) || (KeyCode == 8) || (KeyCode == 46) || (KeyCode > 36 && KeyCode < 41) || (KeyCode == 189)) { return true; } else { return false; } }
4.是否是double型別
function KeyIsDoubleNumber(KeyCode, evalue) {
if (KeyCode == 13) { event.keyCode = 9; return true; }
if (KeyCode == 9) { event.keyCode = 9; return true; }
if ( (KeyCode == 190 || KeyCode == 110)) {
if (evalue.indexOf(".") > -1)
return false;
else if (evalue=="")
return false;
}
if (KeyCode == 13 || KeyCode == 46 || KeyCode == 8 || KeyCode == 110 || KeyCode == 190 || KeyCode == 189 || (KeyCode > 36 && KeyCode < 41) )
return true;
if (KeyCode < 37 || KeyCode > 40 && KeyCode < 48 || (KeyCode > 57 && KeyCode < 96) || KeyCode > 105)
return false;
else
return true;
}
function KeyIsDoubleNumber2(KeyCode, evalue) {
if (KeyCode == 13) { event.keyCode = 9; return true; }
if (KeyCode == 9) { event.keyCode = 9; return true; }
//處理負數必須是第一位輸入
if ((KeyCode == 229 || KeyCode == 109)) {
if (evalue.indexOf("-") > -1)
return false;
else {//如果沒有負數符號加到第一位
event.srcElement.value = "-" + evalue;
return false;
}
}
if ((KeyCode == 190 || KeyCode == 110)) {
if (evalue.indexOf(".") > -1)
return false;
else if (evalue == "")
return false;
}
if (KeyCode == 13 || KeyCode == 46 || KeyCode == 8 || KeyCode == 110 || KeyCode == 190 || KeyCode == 189 || KeyCode == 229 || KeyCode == 109 || (KeyCode > 36 && KeyCode < 41))
return true;
if (KeyCode < 37 || KeyCode > 40 && KeyCode < 48 || (KeyCode > 57 && KeyCode < 96) || KeyCode > 105)
return false;
else
return true;
}
5.時間格式驗證
function DutyCheck(obj) {
var r = /^[0-9]:[0-5][0-9]$|^[0-1][0-9]:[0-5][0-9]$|^[2][0-4]:[0-5][0-9]$/;
if (obj.value != '' && !r.test(obj.value)) {
alert('時間格式不正確');
obj.value = '';
}
}
6.處理鍵盤事件 禁止後退鍵(Backspace)密碼或單行、多行文字框除外
function banBackSpace(e) {
var ev = e || window.event; //獲取event物件
var obj = ev.target || ev.srcElement; //獲取事件源
var t = obj.type || obj.getAttribute('type'); //獲取事件源型別
//獲取作為判斷條件的事件型別
var vReadOnly = obj.getAttribute('readonly');
var vEnabled = obj.getAttribute('enabled');
//處理null值情況
vReadOnly = (vReadOnly == null) ? false : vReadOnly;
vEnabled = (vEnabled == null) ? true : vEnabled;
//當敲Backspace鍵時,事件源型別為密碼或單行、多行文字的,
//並且readonly屬性為true或enabled屬性為false的,則退格鍵失效
var flag1 = (ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea")
&& (vReadOnly == true || vEnabled != true)) ? true : false;
//當敲Backspace鍵時,事件源型別非密碼或單行、多行文字的,則退格鍵失效
var flag2 = (ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea")
? true : false;
//判斷
if (flag2) {
return false;
}
if (flag1) {
return false;
}
}
7.js檔案中使用智慧提示
智慧提示是開發中非常實用的功能,很多軟體都支援js,jquery的智慧提示。不過一般都只能在頁面編輯時智慧提示。
有時候會遇到這種情況:我們定義了js基礎庫Base.js和Script1.js,在Script1.js中引用了許多Base.js中的方法,這時候在Script.js中智慧提示Base.js中的成員就非常必要。
其實方法很簡單:把Base.js檔案往Script.js檔案頂部一拖就行了,在頂部會多出這樣一行程式碼 /// <reference path="../../../js/jquery.js" />
不管是jquery還是自定義的js檔案都可以用這種方法
8.取餘,取整方法
//丟棄小數部分,保留整數部分
parseInt(5/2)
//向上取整,有小數就整數部分加1
Math.ceil(5/2)
//四捨五入.
Math.round(5/2)
//向下取整
Math.floor(5/2)
9.全屏
低版本瀏覽器不支援(IE11)
//全屏
function activeQP(element) {
if (element.requestFullScreen) {
element.requestFullScreen();
} else if (element.webkitRequestFullScreen) {//google
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {//火狐
element.mozRequestFullScreen();
}
else if (element.msRequestFullscreen) {//ie
element.msRequestFullscreen();
}
}
//取消全屏
function deActiveQP() {
// 判斷瀏覽器種類
if (window.parent.document.exitFullscreen) {
window.parent.document.exitFullscreen();
} else if (window.parent.document.mozCancelFullScreen) {//火狐
window.parent.document.mozCancelFullScreen();
} else if (window.parent.document.webkitExitFullscreen) {//google
window.parent.document.webkitExitFullscreen();
}
else if (window.parent.document.msExitFullscreen) {//ie
window.parent.document.msExitFullscreen();
}
}
10.判斷瀏覽器是否為ie7,8
//判斷瀏覽器是否為IE7,8
function IsIE78() {
var browser = navigator.appName
var trim_Version;
if (browser == "Microsoft Internet Explorer") {
var b_version = navigator.appVersion
var version = b_version.split(";");
trim_Version = version[1].replace(/[ ]/g, "");
}
if (browser == "Microsoft Internet Explorer" && (trim_Version == "MSIE7.0" || trim_Version == "MSIE8.0")) {
return true;
} else {
return false;
}
}
11.字串轉json
//把字串轉換為json
function stringToJson(str) {
if (typeof (JSON) == "undefined") {
return eval("(" + str + ")");
} else {
return JSON.parse(str);
}
}
12.獲取字串的位元組長度
//獲取字元的位元組長度
function getCharLength(char) {
return char.replace(/[\u0391-\uffe5]/g, "aa").length;
}
13.去掉空格
function trim(t) {
return t.replace(/(^\s*)|(\s*$)/g, '');
}
14.獲取session值
function getMyName(){
var myName="<%=session.getAttribute("MYNAME")%>";
alert(myName);
}
15.判斷一個物件是否為某個類的例項
overlays[i] instanceof MMap.Control.CustomOverlay
16.獲取url引數
//方法1
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
//呼叫方法
alert(GetQueryString("引數名1")); alert(GetQueryString("引數名2"));
alert(GetQueryString("引數名3"));
//方法2
function GetRequest() {
var url = location.search; //獲取url中"?"符後的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
var Request = new Object();
Request = GetRequest();
var 引數1, 引數2, 引數3, 引數N;
引數1 = Request['引數1'];
引數2 = Request['引數2'];
引數3 = Request['引數3'];
引數N = Request['引數N'];
17.獲取經緯度
// chorme有時候不行,會報如下錯誤
//Network location provider at 'https://www.googleapis.com/' : No response received.
<script>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
console.log(longitude)
console.log(latitude)
},
function (e) {
var msg = e.code;
var dd = e.message;
console.log(msg)
console.log(dd)
}
)
}
</script>
18.獲取ajax請求
var Ajax = {
get: function (url, fn) {
var obj = new XMLHttpRequest(); // XMLHttpRequest物件用於在後臺與伺服器交換資料
obj.open('GET', url, true);
obj.onreadystatechange = function () {
if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) { // readyState == 4說明請求已完成
fn.call(this, obj.responseText); //從伺服器獲得資料
}
};
obj.send();
},
post: function (url, data, fn) { // datat應為'a=a1&b=b1'這種字串格式,在jq裡如果data為物件會自動將物件轉成這種字串格式
var obj = new XMLHttpRequest();
obj.open("POST", url, true);
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 新增http頭,傳送資訊至伺服器時內容編碼型別
obj.onreadystatechange = function () {
if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { // 304未修改
fn.call(this, obj.responseText);
}
};
obj.send(data);
}
}
19.載入js檔案
$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function (_result) {
console.log(remote_ip_info);
if (remote_ip_info.ret == '1') {
alert('國家:' + remote_ip_info.country + '\n省:' + remote_ip_info.province + '\n市:' + remote_ip_info.city + '\n區:' + remote_ip_info.district + '\nISP:' + remote_ip_info.isp + '\n型別:' + remote_ip_info.type + '\n其他:' + remote_ip_info.desc);
} else {
alert('沒有找到匹配的IP地址資訊!');
}
});