Light12306/Mobile12306New/js/util.js

480 lines
12 KiB
JavaScript
Raw Normal View History

2014-08-19 16:11:37 +08:00
var Util = {
/**
* 检测是否是图片文件
* @param {String} f 选定的图片路径
* @return {Boolean} 是否图片
*/
isImageFile: function(f) {
var ext = f.substring(f.lastIndexOf("."), f.length).toLowerCase();
return ext == ".bmp" || ext == ".png" || ext == ".jpg" || ext == ".gif";
},
/**
* 检测对应的选项是否填写
* @param {object} obj 数据容器对象
* @param {String} name 数据项名称
* @param {String} msg 如果没有填写,显示的提示信息
* @return {Boolean}
*/
isEmpty: function(obj, name, msg) {
if (!obj[name]) {
with($("#" + name).addError()) {
if (length > 0) get(0).focus();
}
if (msg) $.showTip(msg);
return true;
}
return false;
},
/**
* 检测数字是否在指定的范围区间中
* @param {Object} v 要检测的值
* @param {Object} min 允许的最小值,不传递或为null则不限制
* @param {Object} max 允许的最大值,不传递或为null则不限制
* @return {Boolean}
*/
checkNumber: function(v, min, max) {
v = parseFloat(v);
return !isNaN(v) && (min == null || v >= min) && (max == null || v <= max);
},
/**
* 转换数字为字符串
* @param {Number} num 要转换的数字
* @param {Number} digits 数字的位数
* @return {String} 转换后的字符串
*/
convertNumberToString: function(num, digits) {
num = '' + num;
var ab = [];
for (var i = 0; i < digits - num.length; i++) {
ab.push("0");
}
return ab.join("") + num;
},
/**
* 转换浮点数为字符串
* @param {Number} num 要转换的数字
* @param {Number} floatDigits 小数位数
* @return {String} 转换后的小数
*/
convertDecimalToString: function(num, floatDigits) {
floatDigits = floatDigits || 2;
num = '' + Math.round(num * (10 ^ floatDigits)) / (10 ^ floatDigits);
var fc = floatDigits;
var idx = num.indexOf(".");
if (idx != -1) fc = floatDigits - num.length - idx - 1;
else num += ".";
var ab = [];
for (var i = 0; i < fc; i++) {
ab.push("0");
}
return num + ab.join("");
},
/**
* 是否点子邮件
* @param {String} str 验证字符串
* @return {Boolean}
*/
isEmail: function(str) {
return /^\w+[\.\-_0-9a-z]+@[0-9a-z]+([\-_\.][0-9a-z]+)*\.(com|net|org|edu|cn)$/i.test(str);
},
/**
* 加载JS
* @param {String} url JS url
* @param {Function} callback 加载成功回调
* @param {String} charset 编码可选
*/
loadJS: function(url, callback, charset) {
/// <summary>加载JS</summary>
var script = document.createElement('script');
script.onload = script.onreadystatechange = function() {
if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;
script.onload = script.onreadystatechange = null;
script.src = '';
script.parentNode.removeChild(script);
script = null;
if (callback) callback();
};
script.charset = charset || document.charset || document.characterSet;
script.src = url;
try {
document.getElementsByTagName("head")[0].appendChild(script);
} catch (e) {}
2014-08-21 13:42:42 +08:00
},
toSeatTypeName : function(code){
switch(code){
case 9:
case '9':
return '商务座';
break;
case 'P':
return '特等座';
break;
case 'M':
return '一等座';
break;
case 'O':
return '二等座';
break;
case 6:
case '6':
return '高级软座';
break;
case 4:
case '4':
return '软卧';
break;
case 3:
case '3':
return '硬卧';
break;
case 2:
case '2':
return '软座';
break;
case 1:
case '1':
return '硬座';
break;
case 0:
case '0':
return '无座';
break;
default :
return '';
}
},
inThatOrder:['O','M','9','3','4','6','1','2','P','0'],
sortType:function(obj){
var arr = [];
for (var i = 0,len = Util.inThatOrder.length; i < len; i++) {
if(typeof obj[Util.inThatOrder[i]] != 'undefined'){
arr.push(obj[Util.inThatOrder[i]]);
}
};
return arr;
},
mapObject:function (array, keySelector) {
var obj = {};
for (var i = 0; i < array.length; i++) {
obj[keySelector(array[i])] = array[i];
};
return obj;
2014-08-21 16:32:56 +08:00
},
canPassageAddToOrder : function (p) {
if (p['passenger_id_type_code'] === "C" || p['passenger_id_type_code'] === "G" || p['passenger_id_type_code'] === "B")
return true;
if (p['passenger_id_type_code'] === "2")
return false;
return p['total_times'] === "93" || p['total_times'] === "95" || p['total_times'] === "97" || p['total_times'] === "99";
}
2014-08-19 16:11:37 +08:00
}
var base64 = {
base64map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("")
};
base64 = $.extend({
base64DeMap: ! function() {
var n = {};
return $.each(base64.base64map, function(t, i) {
n[i] = t
}), n
}(),
encode: function(n) {
for (var t = [], u = base64.base64map, f = n.length, i, r = 0; r < f;) i = n[r] << 16 | n[r + 1] << 8 | n[r + 2], t.push(u[i >> 18], u[i >> 12 & 63], u[i >> 6 & 63], u[i & 63]), r += 3;
return f % 3 == 1 ? (t.pop(), t.pop(), t.push("=", "=")) : (t.pop(), t.push("=")), t.join("")
},
decode: function(n) {
var f = [],
t = n.split(""),
r = base64.base64DeMap,
e = t.length,
u, i = 0;
if (e % 4) return null;
while (i < e) u = r[t[i]] << 18 | r[t[i + 1]] << 12 | r[t[i + 2]] << 6 | r[t[i + 3]], f.push(u >> 16, u >> 8 & 255, u & 255), i += 4;
while (t[--e] == "=") f.pop();
return f
},
encodeArrayBuffer: function(n) {
for (var i = new DataView(n), u = i.byteLength, r = [], t = 0; t < u; t++) r.push(i.getUint8(t));
return base64.encode(r)
},
toObjectUrl: function(n, t) {
return "data:" + t + ";base64," + n
}
}, base64);
//#region Date 扩展
/**
* 表示一个时间差值对象
* @param {Number} count 差值
*/
function DateDifference(count) {
this.TicksCount = count;
/**
* 获得差值的秒数
* @return {Float} 差值的秒数
*/
this.getSeconds = function() {
return this.TicksCount / 1000;
};
/**
* 获得差值的分钟数
* @return {Float} 差值的分钟数
*/
this.getMinutes = function() {
return this.getSeconds() / 60;
};
/**
* 获得差值的小时数
* @return {Float} 差值的小时数
*/
this.getHours = function() {
return this.getMinutes() / 60;
};
/**
* 获得差值的天数
* @return {Float} 差值的天数
*/
this.getDays = function() {
return this.getHours() / 24;
};
/**
* 获得差值的年数大致
* @return {Float} 差值的年数
*/
this.getYears = function() {
return this.getDays() / 365;
};
return this;
}
/**
* 判断当前的日期时间是否合法
* @param {Date} count 验证的日期
* @return {Boolean}
*/
Date.prototype.isValid = function(count) {
return !isNaN(this.getFullYear());
};
/**
* 将日期添加上指定的天数
* @param {Date} count 要添加的天数
*/
Date.prototype.addDays = function(count) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + count);
};
/**
* 将日期添加上指定的月数
* @param {Date} count 要添加的月数
*/
Date.prototype.addMonthes = function(count) {
return new Date(this.getFullYear(), this.getMonth() + count, this.getDate());
};
/**
* 将日期添加上指定的年数
* @param {Date} count 要添加的天数
*/
Date.prototype.addYears = function(count) {
return new Date(this.getFullYear() + count, this.getMonth(), this.getDate());
};
/**
* 将日期减去另一个日期得到二者的差值
* @param {Date} subdate 要减去的日期
* @return {Object} DateDifference
*/
Date.prototype.subtract = function(subdate) {
if (subdate instanceof Date) {
return new DateDifference(this - subdate);
}
return null;
};
/**
* 获得当前日期的天
* @return {Date}
*/
Date.prototype.__defineGetter__("date", function() {
return new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
});
/**
* 格式化日期
* @param {String} format 格式化格式 例如yyyy-MM-dd
* @return {String} 格式化后字符串 例如2014-08-12
*/
Date.prototype.format = function(format) {
format = format || "yyyy-MM-dd";
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
};
if (/(y+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
/**
* 检测是否是今天
*/
Date.prototype.__defineGetter__("isToday", function() {
return this.date.getTime() == (new Date()).date.getTime();
});
/**
* 获取星期
* @param {Number} len 格式化后字符串长度
* @return {String} 格式化后的星期几
*/
Date.prototype.day = function(len) {
var days = ['日', '一', '二', '三', '四', '五', '六'];
switch (len) {
case 1:
return days[this.getDay()];
break;
case 2:
return '周' + days[this.getDay()];
break;
default:
return '星期' + days[this.getDay()];
break;
}
};
//#endregion
//#region String扩展
function asDate(s) {
if (/\/Date\((\d+)\)\//i.exec(s)) {
return new Date(parseInt(RegExp.$1));
}
if (/(\d+)-0*(\d+)-0*(\d+)T0*(\d+):0*(\d+):0*(\d+)/i.exec(s)) {
return new Date(parseInt(RegExp.$1), parseInt(RegExp.$2) - 1, parseInt(RegExp.$3), parseInt(RegExp.$4), parseInt(RegExp.$5), parseInt(RegExp.$6));
}
if (/(\d{4})-0?(\d{1,2})-0?(\d{1,2})/.exec(s)) {
return new Date(RegExp.$1, RegExp.$2 - 1, RegExp.$3);
}
return new Date(s);
}
String.prototype.toDate = function() {
return asDate(this + "");
};
String.prototype.padLeft = function(len, str) {
/// <summary>将字符串左侧进行填充至指定长度</summary>
if (this.length >= len) {
return this;
}
var s = [];
while (s.length + this.length < len) {
s.push(str);
}
return s.join("") + this;
};
String.prototype.padRight = function(len, str) {
/// <summary>将字符串右侧进行填充至指定长度</summary>
if (this.length >= len) {
return this;
}
var s = [];
while (s.length + this.length < len) {
s.push(str);
}
return this + s.join("");
};
String.prototype.format = function(format, str) {
/// <summary>格式化字符串</summary>
var number = parseInt(format);
return number > 0 ? this.padLeft(number, str || ' ') : this.padRight(number, str || ' ');
};
String.prototype.temp = function(a) {
return this.replace(/\$\w+\$/gi, function(b) {
b = a[b.replace(/\$/g, "")];
return b + "" == "undefined" ? "" : b;
});
};
//#endreigon
//#region 数值扩展
Number.prototype.toSize = function() {
/// <summary>转换为内容大小表示</summary>
var array = ["字节", "KB", "MB", "GB", "TB"];
var index = 0;
var i = this * 1.0;
while (i > 1000 && index < array.length) {
index++;
i = i / 1024.0;
}
return Math.round(i * 100) / 100 + array[index];
};
Number.prototype.format = function(format) {
/// <summary>对数值进行格式化</summary>
// 进制|整数长度|小数长度
var args = format.split(':');
var strValue = this.toString(args[0] || 10);
if (!args[1]) {
return strValue;
}
var parts = strValue.split(".");
var _int = "";
var _float = "";
if (args[1]) {
//整数
_int = parts[0].padLeft(args[1], '0');
} else {
_int = parts[0];
}
_float = args[2] ? (parts[1] || "").padRight(args[2], '0') : (parts[1] || "");
return _int + (_float ? "." : "") + _float;
};
Boolean.prototype.format = function(format) {
var args = format.split(':');
return this == true ? args[0] : args[1];
};