- 浏览: 495959 次
- 性别:
- 来自: 广州
文章分类
- 全部博客 (502)
- Java (70)
- Linux (10)
- 数据库 (38)
- 网络 (10)
- WEB (13)
- JSP (4)
- 互联网 (71)
- JavaScript (30)
- Spring MVC (19)
- HTML (13)
- CSS (3)
- AngularJS (18)
- Redis (5)
- Bootstrap CSS (1)
- ZooKeeper (4)
- kafka (6)
- 服务器缓存 (4)
- Storm (1)
- MongoDB (9)
- Spring boot (16)
- log4j (2)
- maven (3)
- nginx (5)
- Tomcat (2)
- Eclipse (4)
- Swagger (2)
- Netty (5)
- Dubbo (1)
- Docker (7)
- Hadoop (12)
- OAuth (1)
- webSocket (4)
- 服务器性能 (7)
- Session共享 (1)
- tieye修改 (1)
- 工作 (1)
- 有用的语录 (0)
- https (2)
- common (5)
- 产品开发管理 (1)
- CDN 工作原理 (1)
- APNS、GCM (1)
- 架构图 (3)
- 功能实现分析 (1)
- JMX (1)
- 服务器相关操作命令 (1)
- img02 (0)
- 服务器环境搭建 (9)
- goodMenuBook (1)
- CEInstantPot (0)
- 有用数据 (1)
- 百度地图WEB API (2)
- 正则表达式 (1)
- 样式例子 (2)
- staticRecipePressureCooker.zip (1)
- jCanvas (1)
- 网站攻击方法原理 (1)
- 架构设计 (3)
- 物联网相关 (3)
- 研发管理 (7)
- 技术需求点 (1)
- 计划 (1)
- spring cloud (11)
- 服务器开发的一些实用工具和方法 (1)
- 每天学到的技术点 (4)
- Guava (1)
- ERP 技术注意要点 (2)
- 微信小程序 (1)
- FineRepor (1)
- 收藏夹 (1)
- temp (5)
- 服务架构 (4)
- 任职资格方案 (0)
- osno_test (1)
- jquery相关 (3)
- mybatis (4)
- ueditor (1)
- VueJS (7)
- python (10)
- Spring EL (1)
- shiro (1)
- 前端开发原理与使用 (7)
- YARN (1)
- Spark (1)
- Hbase (2)
- Pig (2)
- 机器学习 (30)
- matplotlib (1)
- OpenCV (17)
- Hystrix (1)
- 公司 (1)
- miniui (4)
- 前端功能实现 (3)
- 前端插件 (1)
- 钉钉开发 (2)
- Jenkins (1)
- elasticSearch使用 (2)
- 技术规范 (4)
- 技术实现原理 (0)
最新评论
//本包使用需要先引入jquery
//获取数组中的重复元素,返回重复元素数组
function getArrayDuplicate(array) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]]) {
checkResultTmep.push(array[i])
} else {
checkTmep[array[i]] = "true";
}
}
return checkResultTmep;
}
//获取数组中的去重后的元素数组
function getArrayNotDuplicate(array) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]]) {
} else {
checkTmep[array[i]] = "true";
checkResultTmep.push(array[i])
}
}
return checkResultTmep;
}
//获取对象数组中的重复元素,返回重复元素数组
function getObjArrayDuplicate(array, field) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]][field]) {
checkResultTmep.push(array[i])
} else {
checkTmep[array[i]] = "true";
}
}
return checkResultTmep;
}
//检查电话号码是否符合要求
function isPhoneNum(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone);
}
//post方式下载文件,params为object
function postDownloadFile(downloadrl, params) {
// 创建form元素
var tempForm = document.createElement("form");
// 设置form属性
tempForm.action = url;
tempForm.target = "_self";
tempForm.method = "post";
tempForm.style.display = "none";
// 处理需要传递的参数
for (var x in params) {
var opt = document.createElement("textarea");
opt.name = x;//参数名
opt.value = params[x]; //参数值
tempForm.appendChild(opt); //
}
document.body.appendChild(temp_form);
// 提交表单
tempForm.submit();
}
//JSON串转Object
function jsonStringToObj(JsonString) {
try {
return JSON.parse(JsonString);
} catch (err) {
alert(err); // 可执行
alert(JsonString); // 可执行
throw err;
}
}
//Object转JSON串
function jsonObjToString(object) {
try {
return JSON.stringify(object);
} catch (err) {
alert(err); // 可执行
alert(JsonString); // 可执行
throw err;
}
}
//通过ID显示元素
function showElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).show();
}
}
//通过ID隐藏元素
function hideElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).hide();
}
}
//通过ID禁用元素
function disabledElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " input";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " button";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " a";
$(idSelect).attr('disabled', true).css("pointer-events", "none");
}
}
//通过ID不禁用元素
function enabledElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).attr('disabled', false);
idSelect = "#" + idArray[i] + " input";
$(idSelect).attr('disabled', false);
idSelect = "#" + idArray[i] + " button";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " a";
$(idSelect).attr('disabled', false).css("pointer-events", "auto");
}
}
//获取From中的数据object
function getFormData(fromId) {
var formArray = $("#" + fromId).serializeArray();
var formObject = {};
$.each(formArray, function (i, item) {
if (formObject[item.name]) {
formObject[item.name] = formObject[item.name] + "," + item.value;
} else {
formObject[item.name] = item.value;
}
});
return formObject;
}
function setFormData(selector, data) {
if (data) {
for (var key in data) {
var el = $(selector + " [name='" + key + "']");
// commonConsole(el[0],"el[0]")
var value = data[key];
if (el[0].tagName == "SELECT") {
value = value.split(',')
} else if (el[0].tagName == "INPUT" && el[0].type == "checkbox") {
value = value.split(',')
} else if (el[0].tagName == "INPUT" && el[0].type == "radio") {
value = value.split(',')
} else {
value = data[key];
}
// commonConsole(value,"value")
// commonConsole(key,"key")
el.val(value);
}
}
}
//为指定元素加入粘贴事件处理,IE不能在非输入框中触发这个事件
// function addPasteByElement(elementId,onPasteFun) {
// $('#'+elementId ).bind({
// paste: function(e) { //paste事件
// var eve = e.originalEvent
// var cp = eve.clipboardData;
// var data=undefined;
// var clipboardData = window.clipboardData; // IE
// if (!clipboardData) { //chrome
// clipboardData = e.originalEvent.clipboardData
// }
// data = clipboardData.getData('Text');
// if(onPasteFun){
// onPasteFun(data,e.target);
// }
// }
// });
// }
function addPasteByElement(elementId, onPasteFun) {
if (compatibleBrowser()) {
$('#' + elementId).bind({
paste : function (e) { //paste事件
var eve = e.originalEvent
var cp = eve.clipboardData;
var data = undefined;
var clipboardData = window.clipboardData; // IE
if (!clipboardData) { //chrome
clipboardData = e.originalEvent.clipboardData
}
data = clipboardData.getData('Text');
onPasteFun(data, e.target);
}
});
} else {
$('#' + elementId).attr("tabindex", "0");
$('#' + elementId).bind("keydown", function (e) {
if (e.ctrlKey && e.keyCode == 86) { //ctrl + v
// alert("ctrl + v");
// alert(e.target.id);
if (e.target.id == elementId) {
var clipboardData = window.clipboardData; // IE
data = clipboardData.getData('Text');
onPasteFun(data, e.target);
}
}
});
}
}
//粘贴板中excel的内容以行字符串数组返回[]
function getExcelRowStringArray(pasteData) {
var excelData = [];
if (!pasteData) {
return excelDataArray;
}
var newArr = [];
if (typeof pasteData === "string") {
newArr = pasteData.split("\n");
if (newArr.length > 0) {
for (i = 0; i < newArr.length; i++) {
var item = newArr[i];
newArr[i] = item.replace(/\"/g, "").replace(/(^\s*)/g, "")
.replace(/(\s*$)/g, "");
}
excelData = newArr.slice(0, newArr.length - 1);
}
}
return excelData;
}
//粘贴板中excel的内容以行列二维数组返回[][]
function getExcelRowsArray(excelRowStringArray) {
var excelRowsArray = [];
if (!excelRowStringArray) {
return excelRowsArray;
}
for (var i = 0; i < excelRowStringArray.length; i++) {
var item = excelRowStringArray[i];
var strArray = item.split("\t");
excelRowsArray[i] = strArray;
}
return excelRowsArray;
}
//浏览器IE为false,其他为true
function compatibleBrowser() {
var userAgent = window.navigator.userAgent;
if (userAgent.indexOf("Chrome") > -1 || userAgent.indexOf("Firefox") > -1
|| userAgent.indexOf("Opera") > -1) {
return true;
} else {
return false;
}
}
//对象按对应关系转换key
// var fieldMappingObj ={};
// fieldMappingObj.id = 'idNum'; //id转换为idNum
// fieldMappingObj.pid = 'pidNum';
function ObjChangeField(obj, fieldMappingObj) {
if (!obj) {
throw 'obj undefined';
}
if (!fieldMappingObj) {
return obj;
}
var returnObj = {};
for (var key in obj) {
var value = obj[key];
var mapToKey = fieldMappingObj[key];
//有就进行key的更换,没有就按原有key输出
if (mapToKey) {
returnObj[mapToKey] = value;
} else {
returnObj[key] = value;
}
}
return returnObj;
}
//对象数组按对应关系转换key
// var fieldMappingObj ={};
// fieldMappingObj.id = 'idNum'; //id转换为idNum
// fieldMappingObj.pid = 'pidNum';
function ObjListChangeField(objList, fieldMappingObj) {
if (!objList) {
throw 'objList undefined';
}
if (!objList.length) {
throw 'objList length undefined';
}
var returnObjArray = [];
for (var i = 0; i < objList.length; i++) {
var obj = objList[i];
var returnObj = ObjChangeField(obj, fieldMappingObj);
returnObjArray.push(returnObj);
}
return returnObjArray;
}
//对象复制(浅度复制)
function copyObj(obj) {
if (!obj) {
throw 'obj undefined';
}
var returnObj = {};
for (var key in obj) {
var value = obj[key];
returnObj[key] = value;
}
return returnObj;
}
//对象深度复制(深度复制)
function deepClone(obj) {
let newObject;
if (obj === null) {
return null;
}
else if (!(obj instanceof Object)) {
return obj;
}
else if (obj instanceof Date) {
return new Date(obj);
}
else if (obj instanceof Function) {
return Object.assign(obj);
}
else if (obj instanceof RegExp) {
return new RegExp(obj);
}
else if (obj instanceof Array) {
newObject = [];
for (item of
obj
)
{
newObject.push(Object.deepClone(item));
}
}
else {
newObject = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
for (let key of
Object.keys(obj)
)
{
if (newObject[key] != obj) {
newObject[key] = Object.deepClone(obj[key]);
} else {
newObject[key] = newObject;
}
}
}
return newObject;
}
//目录树按key和value进行过滤,返回符合的树结构(childrenKey-->childrenListKey)
function menuTreeFilterByKeyValue(menuList, key, value, childrenKey) {
if (!menuList) {
throw 'menuList undefined';
}
function nodeFillNewFromOld(oldNode, childrenKey) {
var newNode = copyObj(oldNode);
newNode[childrenKey] = undefined;
return newNode;
}
function checkNodeEquals(node, key, value) {
if (!node[key]) {
return false;
}
if (node[key].indexOf(value) != -1) {
return true;
} else {
return false;
}
}
var menuNew = [];
for (var i = 0; i < menuList.length; i++) {
var nodeNew = undefined;
var node = menuList[i];
var childrenNode = node.children;
var childrenMenu = [];
if (childrenNode) {
if (childrenNode.length > 0) {
childrenMenu = menuFilterByKeyValue(childrenNode, key, value, childrenKey);
}
}
if (childrenMenu) {
if (childrenMenu.length > 0) {
nodeNew = new Object();
nodeNew = nodeFillNewFromOld(node, childrenKey);
nodeNew.children = childrenMenu;
} else {
if (checkNodeEquals(node, key, value)) {
nodeNew = new Object();
nodeNew = nodeFillNewFromOld(node, childrenKey);
}
}
}
if (nodeNew) {
menuNew.push(nodeNew);
}
}
return menuNew;
}
//List转换为Tree结构
function listToTree(list, childKey, parentKey, childListKey) {
function listToObjMap(list, key) {
if (!list) {
throw 'list undefined';
}
if (!key) {
throw 'key undefined';
}
var objMap = {};
for (var i = 0; i < list.length; i++) {
var obj = list[i];
var objKey = obj[key];
if (objMap[objKey]) {
objMap[objKey].push(obj);
} else {
objMap[objKey] = [];
objMap[objKey].push(obj);
}
}
return objMap;
}
function listToTreeFor(listTop, childKey, parentMap, childListKey) {
if (!listTop) {
throw 'listTop undefined';
}
if (!childKey) {
throw 'childKey undefined';
}
if (!parentMap) {
throw 'parentMap undefined';
}
var treeObjArray = [];
for (var i = 0; i < listTop.length; i++) {
var obj = listTop[i];
var childKeyValue = obj[childKey];
if (!childKeyValue) {
throw 'childKeyValue undefined';
}
var listTopTemp = parentMap[childKeyValue];
var objTemp = copyObj(obj);
if (listTopTemp) {
var childList = listToTreeFor(listTopTemp, childKey, parentMap, childListKey);
objTemp[childListKey] = childList;
treeObjArray.push(objTemp);
} else {
treeObjArray.push(objTemp);
}
}
return treeObjArray;
}
if (!list) {
throw 'list undefined';
}
if (!childKey) {
throw 'childKey undefined';
}
if (!parentKey) {
throw 'parentKey undefined';
}
if (!childListKey) {
throw 'childListKey undefined';
}
var map = listToObjMap(list, parentKey);
var mapChild = listToObjMap(list, childKey);
//子里面没有的就是顶级元素
var listTopTemp = [];
for (var key in map) {
var objArray = mapChild[key];
if (!objArray) {
// listTopTemp.push(map[key]);
var tempArray = map[key];
if (tempArray.length > 0) {
for (var i = 0; i < tempArray.length; i++) {
listTopTemp.push(tempArray[i])
}
}
// listTopTemp.concat(map[key]);
}
}
if (listTopTemp.length == 0) {
throw 'top list is empty';
}
var treeObj = listToTreeFor(listTopTemp, childKey, map, childListKey);
return treeObj;
}
function getTimestamp(dateTemp) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
return value;
}
function dateAddMs(dateTemp, numMs) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
value += numMs; //将天数转换成毫秒后与开始时间相加得到结束时间的毫秒数
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
return dateTemp2;
}
function dateAddSecond(dateTemp, numSecond) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setSeconds(dateTemp2.getSeconds() + numSecond);
return dateTemp2;
}
function dateAddMinute(dateTemp, numMinute) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setMinutes(dateTemp2.getMinutes() + numMinute);
return dateTemp2;
}
function dateAddHour(dateTemp, numHours) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setHours(dateTemp2.getHours() + numHours);
return dateTemp2;
}
function dateAddDate(dateTemp, numDate) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setDate(dateTemp2.getDate() + numDate);
return dateTemp2;
}
function dateAddYear(dateTemp, numYear) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setYear(dateTemp2.getYear() + numYear);
return dateTemp2;
}
function dateAddMonth(dateTemp, numMonth) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setMonth(dateTemp2.getMonth() + numMonth);
return dateTemp2;
}
//计算地图上的距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
function getMapDistance(lat1, lng1, lat2, lng2) {
function Rad(d) {
return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}
var radLat1 = Rad(lat1);
var radLat2 = Rad(lat2);
var a = radLat1 - radLat2;
var b = Rad(lng1) - Rad(lng2);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137;// EARTH_RADIUS;
s = Math.round(s * 10000) / 10000; //输出为公里
//s=s.toFixed(4);
return s;
}
function convertBase64UrlToBlob(urlData) {
if (!urlData) {
urlData = '';
}
var bytes = urlData; //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {type : 'image/jpg'});
}
//移动端向body输出执行错误信息
function showErrorMsgToBody(msg) {
var temp = $("#commonErrorMsgInfo")[0];
if (!temp) {
$("body").append('<textarea id="commonErrorMsgInfo" style="width: 98%;" rows="30"></textarea>');
}
$("#commonErrorMsgInfo").val(msg); //方法2
}
//替换字符
function replaceAll(srcStr, findStr, replaceStr) {
var temp = srcStr.replace(new RegExp(findStr, 'g'), replaceStr);
return temp;
}
//时间转字符串
//"yyyy-MM-dd hh:mm:ss",yyyy/MM/dd hh:mm:ss
function dateFormat(date, fmt) {
var o = {
"M+" : date.getMonth() + 1, //月份
"d+" : date.getDate(), //日
"h+" : date.getHours(), //小时
"m+" : date.getMinutes(), //分
"s+" : date.getSeconds(), //秒
"q+" : Math.floor((date.getMonth() + 3) / 3), //季度
"S" : date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
//获取这的开始时间
function getFirstTimeOfDate(date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取这周的周一
function getFirstDayOfWeek(date) {
var weekday = date.getDay() || 7; //获取星期几,getDay()返回值是 0(周日) 到 6(周六) 之间的一个整数。0||7为7,即weekday的值为1-7
date.setDate(date.getDate() - weekday + 1);//往前算(weekday-1)天,年份、月份会自动变化
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当月第一天
function getFirstDayOfMonth(date) {
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当季第一天
function getFirstDayOfSeason(date) {
var month = date.getMonth();
if (month < 3) {
date.setMonth(0);
} else if (2 < month && month < 6) {
date.setMonth(3);
} else if (5 < month && month < 9) {
date.setMonth(6);
} else if (8 < month && month < 11) {
date.setMonth(9);
}
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当年第一天
function getFirstDayOfYear(date) {
date.setMonth(0);
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
////该月第一个周几的日期(1-7)
//function getFirstWeekdayOfMonday(year, month, weekday){
// var date = new Date();
// // 该月第一天
// date.setFullYear(year);
// date.setMonth(month);
// date.setDate(1);
// date.setHours(0);
// date.setMinutes(0);
// date.setSeconds(0);
// date.setMilliseconds(0);
// var w1 = date.getDay();
// if (w1 == 0) {
// w1 = 7;
// }
// var addDate=0;
// if(weekday>=w1){
// addDate = weekday - w1
// }else{
// addDate = 7+weekday - w1;
// }
// date.setDate(date.getDate() + addDate);
// return date;
//}
////该月第一个周几的日期(1-7)
function getFirstWeekdayOfMonday(dateTemp, weekday) {
var date = new Date();
// 该月第一天
date.setFullYear(dateTemp.getFullYear());
date.setMonth(dateTemp.getMonth());
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var w1 = date.getDay();
if (w1 == 0) {
w1 = 7;
}
var addDate = 0;
if (weekday >= w1) {
addDate = weekday - w1
} else {
addDate = 7 + weekday - w1;
}
date.setDate(date.getDate() + addDate);
return date;
}
//读取文件DataURL
function readImageFileAsDataURL(file, onloadFun) {
var fileReader = new FileReader();//创建new FileReader()对象
var imgObj = file;//获取图片
fileReader.readAsDataURL(imgObj);//将图片读取为DataURL
fileReader.onload = function (e) {
if (onloadFun) {
onloadFun(e)
}
};
}
//进入调试模式
$(function () {
$('body').append(
'<div style="width: 100%;height: 25px;background-color: #fffff8" onclick="debugKeyClickFun()"></div>');
});
var debugKeyTimeOutEvent = 0;
var debugKeyTimeNums = 0;
function debugKeyClickPressFun() {
console.info("debugKeyTimeNums ==" + debugKeyTimeNums);
if (debugKeyTimeNums >= 10) {
console.info("长按事件触发发");
erudaDebugEnterFun();
}
debugKeyTimeNums = 0;
debugKeyTimeOutEvent = 0;
}
function debugKeyClickFun() {
console.info("debugKeyClickFun");
if (debugKeyTimeOutEvent == 0) {
debugKeyTimeOutEvent = setTimeout("debugKeyClickPressFun()", 5000);
debugKeyTimeNums = debugKeyTimeNums + 1;
} else {
debugKeyTimeNums = debugKeyTimeNums + 1;
}
}
var erudaDebugTest = 0;
function erudaDebugEnterFun() {
if (erudaDebugTest == 0) {
erudaDebugTest = 1;
var script = document.createElement('script');
script.src = "http://eruda.liriliri.io/eruda.min.js";
document.body.appendChild(script);
script.onload = function () {
eruda.init();
}
}
}
//进行图片压缩(返回base64),rate压缩比(0.8),completeFun(data)压缩完回调
function compressImageData(srcData, quality, completeFun) {
var image = new Image();
image.src = srcData;
image.onload = function () {
var expectWidth = this.naturalWidth;
var expectHeight = this.naturalHeight;
if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 1000) {
expectWidth = 1000;
expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
} else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1400) {
expectHeight = 1400;
expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = expectWidth;
canvas.height = expectHeight;
ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
var dataReturn = canvas.toDataURL("image/jpeg", quality);
if (completeFun) {
completeFun(dataReturn)
}
};
}
//元素是否隐藏
function elementIsHide(selector) {
var temp = $(selector).is(":hidden");
return temp;
}
//元素是否显示
function elementIsShow(selector) {
var temp = $(selector).is(":visible");
return temp;
}
//Debug格式输出
function logDebug(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
//Info格式输出
function logInfo(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
function commonConsole(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
//获取HTML的STRING
function elementToString(selector) {
var temp = $(selector).prop("outerHTML");
return temp;
}
//获取Iframe的运行环境,用以运行其内的相关函数
function getIframeContentWindow(iframe) {
return iframe.contentWindow;
}
//用一个对象中的值赋给另一个对象(按字段名进行)
function objSetObjByField(srcObj, targetObj) {
if (!srcObj) {
throw 'srcObj undefined';
}
if (!targetObj) {
throw 'targetObj undefined';
}
for (var key in srcObj) {
if (key in targetObj) {
targetObj[key] = srcObj[key];
}
}
return targetObj;
}
//检验电话号码
function checkPhone(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone.trim());
}
//检验身份证号码
function checkPeopleCard(cardNum) {
var reg = /^[\d]{17}[0-9|X|x]{1}$/;
return reg.test(cardNum.trim());
}
//邮政编码号码
function checkPostcode(cardNum) {
var reg = /^[\d]{6}/;
return reg.test(cardNum.trim());
}
//设置属性值
function setAttrValue(selector, attribute, value) {
$(selector).attr(attribute, value);
}
//获取属性值
function getAttrValue(selector, attribute) {
return (selector).attr(attribute);
}
//hasAttr
function hasAttr(selector, attribute) {
if (typeof ($(selector).attr(attribute)) == "undefined") {
return false;
} else {
return true;
}
}
//addClass
function addClass(selector, clazz) {
return $(selector).addClass(clazz);
}
//removeClass
function removeClass(selector, clazz) {
return $(selector).removeClass(clazz);
}
//是否包含指定的 class
function hasClass(selector, clazz) {
return $(selector).hasClass(clazz);
}
//是否是num
function isNumber(value) {
var reg = (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/);
var flag = reg.test((value + '').trim());
return flag;
}
//是否是整数
function isInt(value) {
var reg = /^-?\d+$/;
var flag = reg.test((value + '').trim());
return flag;
}
//检验电话号码
function isPhone(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone.trim());
}
//检验身份证号码
function isPeopleCard(cardNum) {
var reg = /^[\d]{17}[0-9|X|x]{1}$/;
return reg.test(cardNum.trim());
}
//检验邮箱地址号码
function isEmail(emailNum) {
var reg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
return reg.test(emailNum.trim());
}
//对象里的内容前后去空格(trim)
function objTrim(obj) {
if (obj) {
for (var key in obj) {
obj[key] = obj[key].trim();
}
}
return obj;
}
//数字范围检测
function numberRangeCheck(val, minVal, maxVal) {
var flag = isNumber(val);
if (!flag) {
throw val + "不是数字";
}
if (minVal != null && minVal != undefined) {
var flag = isNumber(minVal);
if (!flag) {
throw "最小值:" + minVal + "不是数字";
}
if (val < minVal) {
throw val + " < " + minVal + ",小于最小值:" + minVal;
}
}
if (maxVal != null && maxVal != undefined) {
var flag = isNumber(maxVal);
if (!flag) {
throw "最大值:" + maxVal + "不是数字";
}
if (val > maxVal) {
throw val + " > " + maxVal + ",大于最大值:" + maxVal;
}
}
}
//字符长度检测
function stringLenCheck(val, minLen, maxLen) {
if (val == null || val == undefined) {
throw "值为:" + val + ",不为字符串";
}
val = val.trim();
if (minLen != null && minLen != undefined) {
var flag = isInt(minLen);
if (!flag) {
throw "最小长度:" + minLen + "不是数字";
}
if (val.length < minLen) {
throw val + " 长度 < 最小长度 " + minLen;
}
}
if (maxLen != null && maxLen != undefined) {
var flag = isInt(maxLen);
if (!flag) {
throw "最大长度:" + maxLen + "不是数字";
}
if (val.length > maxLen) {
throw val + " 长度 > 最大长度 " + maxLen;
}
}
}
//字符串不为空检测
function requiredCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",为空字符串";
}
}
//int检测
function intCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",不为整数";
}
var flag = isInt(val);
if (!flag) {
throw val + "不是整数";
}
}
//email检测
function emailCheck(val) {
if (val != null && val != undefined) {
var flag = isEmail(val);
if (!flag) {
throw val + "不是正确的电子邮件地址";
}
}
}
//number检测
function numberCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",不为数字";
}
var flag = isNumber(val);
if (!flag) {
throw val + "不是数字";
}
}
//数据校验
//dataOption={id:id,required:}
function valValidateCheck(val, dataOption, validateCallFun) {
//dataOption中那些key要校验的
var validateKey = {
required : true,
email : true,
url : true,
number : true,
int : true,
maxLen : true,
minLen : true,
range : true,
max : true,
min : true
}
var defaultDataOptionMsg = {
required : "这是必填字段",
email : "请输入有效的电子邮件地址",
url : "请输入有效的网址",
number : "请输入有效的数字",
int : "请输入整数",
maxLen : "字符串长度应小于设置值",
minLen : "字符串长度应大于设置值",
max : "数值应小于设置值",
min : "数值应大于设置值",
}
if (dataOption) {
for (var key in dataOption) {
var checkFlag = validateKey[key];
// logDebug(checkFlag, "checkFlag");
if (!checkFlag) {
continue;
}
//
try {
if (key == "required") {
requiredCheck(val);
} else if (key == "email") {
emailCheck(val);
} else if (key == "number") {
numberCheck(val)
} else if (key == "int") {
intCheck(val)
} else if (key == "maxLen" || key == "minLen") {
var minLen = dataOption['minLen'];
var maxLen = dataOption['maxLen'];
stringLenCheck(val, minLen, maxLen);
} else if (key == "max" || key == "min") {
var minVal = dataOption['min'];
var maxVal = dataOption['max'];
numberRangeCheck(val, minVal, maxVal);
} else if (key == "url") {
//numberCheck(val)
}
//用于
var msg = "";
var elementId = dataOption['id'];
if (validateCallFun) {
validateCallFun(elementId, msg);
} else {
defaultValidateCallFun(elementId, msg);
}
} catch (err) {
var msg = defaultDataOptionMsg[key];
var lable = dataOption['lable'];
var elementId = dataOption['id'];
if (lable) {
msg = '字段名:' + lable + ",\n" + err + ',\n 设置要求:' + msg;
}
if (validateCallFun) {
validateCallFun(elementId, msg);
} else {
defaultValidateCallFun(elementId, msg);
}
throw msg;
}
}
}
}
//数据校验默认处理
function defaultValidateCallFun(elementId, msg) {
if(msg==''){
$('#' + elementId).removeClass("validateErrorShow");
}else{
$('#' + elementId).addClass("validateErrorShow");
// openAlert(msg);
// alert(msg);
commonConsole(msg,"msg");
}
}
//from数据校验Init
function formValidateInit(dataOptionForName, validateCallFun) {
if (dataOptionForName) {
if (!validateCallFun) {
validateCallFun = defaultValidateCallFun();
}
for (var key in dataOptionForName) {
var dataOption = dataOptionForName[key];
if (!dataOption) {
continue;
}
var id = dataOption["id"];
if (!id) {
continue;
}
var temp = $('#' + id);
if (!temp) {
continue;
}
var changeFun = (function (id, dataOption, validateCallFun) {
return function () {
var val = $('#' + id).val();
try {
valValidateCheck(val, dataOption, validateCallFun);
} catch (err) {
openAlert(err);
}
// valValidateCheck(val, dataOption, validateCallFun);
}
})(id, dataOption, validateCallFun);
temp.change(changeFun); //值改变事件
temp.blur(changeFun);//失去焦点事件
// commonConsole(changeFun,'changeFun');
}
}
}
//from数据校验
function getFormDataValidateMsgList(data, dataOptionForName, validateCallFun) {
var validateMsgList = [];
if (data) {
for (var key in data) {
var dataOption = dataOptionForName[key];
if (dataOption) {
var val = data[key];
try {
valValidateCheck(val, dataOption, validateCallFun);
} catch (err) {
var lable = dataOption['lable'];
var id = dataOption['id'];
var name = dataOption['name'];
var msg = err;
var obj = {
id : id,
lable : lable,
name : name,
msg : msg,
dataOption : dataOption
}
validateMsgList.push(obj);
}
}
}
}
return validateMsgList;
}
//获取非空字符串
function getNotEmptyString(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return "";
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return "";
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//获取非空数字(如果是字符串返字符串)
function getNotEmptyNum(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//treeToList
function treeToList(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//向array加入array
function listAddList(toList, addList) {
for (var i = 0; i < addList.length; i++) {
toList.push(addList[i]);
}
return toList;
}
//var test = treeToList(data,"id","pId","child","text","text2","0","");
//树数据转平面数据,文字有层次表示
function treeToList(treeList, childKey, parentKey, childListKey, textKey, textJoinKey, parentValue, parentTextJoinValue) {
var listReturn = [];
var list = treeList;
for (var i = 0; i < list.length; i++) {
var obj = list[i];
// var childKeyTemp = obj[childKey];
var parentValueTemp = obj[childKey];
var parentTextJoinValueTemp = "";
if (parentTextJoinValue == "") {
parentTextJoinValueTemp = obj[textKey];
} else {
parentTextJoinValueTemp = parentTextJoinValue + "->" + obj[textKey];
}
// var parentTextJoinValueTemp = parentTextJoinValue +"->"+ obj[textKey];
var childList = obj[childListKey];
if (childList) {
var listReturnTemp = treeToList(childList, childKey, parentKey, childListKey, textKey, textJoinKey, parentValueTemp, parentTextJoinValueTemp);
listReturn = listAddList(listReturn, listReturnTemp);
}
obj[parentKey] = parentValue;
obj[textJoinKey] = parentTextJoinValueTemp;
listReturn.push(obj);
}
return listReturn;
}
//post提交下载附件
function requestPost(url, parameters) {
var _form = $("<form>");
_form.attr("style", "display:none");
_form.attr("method", "post");
_form.attr("action", url);
$("body").append(_form);
for (var i = 0; i < parameters.length; i++) {
var obj = parameters[i];
var _input = $("<input>");
_input.attr("type", "hidden");
_input.attr("name", obj.name);
_input.attr("value", obj.value);
_form.append(_input);
}
_form.submit();
}
//是否禁用控件
function elementEnabled(elementId, enabledFlag) {
mini.get(elementId).setEnabled(enabledFlag);
}
//是否显示控件
function elementShow(elementId, enabledFlag) {
mini.get(elementId).setVisible(enabledFlag);
}
//是否允许文本输入
function elementAllowInput(elementId, enabledFlag) {
mini.get(elementId).setAllowInput(enabledFlag);
}
//数字转货币形式(参数:数字,保留小数位数,货币符号,整数部分千位分隔符,小数分隔符)
// formatMoney(158479.234, 2, "¥ ", ",", ".")
function formatMoney(number, places, symbol, thousand, decimal) {
number = number || 0;
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return symbol + negative + (j ? i.substr(0, j) + thousand : "") +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" +
thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}
//处理Textarea的字符串
function dealTextareaString(str) {
return str.replace(/\n/g, '\\n').replace(/\r\\n/g, '\\n');
}
//select2Make
function select2Make(selector, dataArry) {
//选择列表初始数据
$(selector).select2({
data : dataArry
});
}
//setSelect2
function setSelect2(selecto, idArray) {
$(selector).val(idArray).trigger('change'); //设置值
}
////判断是否图片类型
function isImageType(file) {
var pictype = file.type;
var type = pictype.split("/")[1];//判断是否图片类型
if (type === "bmp" || type === "tiff" || type === "gif" || type === "jpeg" ||
type === "exif" || type === "png" || type === "raw" || type === "jpg") {
return true;
} else {
return false;
}
}
function commonConsole(data, dataStr) {
console.info("==================== " + dataStr);
console.info(data);
console.info("-------------------- ");
}
//指定特殊字符检测
//var value2 = {
// name:'name',
// arr:[{
// name2:'name2?'
// }],
// sex:15
//}
//
//var specialCharList = ['"','?'];
//
//specialCharCheck(value2,specialCharList);
function stringHasSpecialCharCheck(value,specialCharList){
if(!value){
return;
}
if(typeof(value) == "string" ){
if(specialCharList){
for(var i=0;i<specialCharList.length;i++){
var char = specialCharList[i];
if(value.indexOf(char)>=0){
throw "\"" + value + "\"包含有\"" + char + "\"字符";
}
}
}
}
}
function specialCharCheck(obj,specialCharList){
if(!obj){
return;
}
if(obj instanceof Array){
for(var i=0;i<obj.length;i++){
specialCharCheck(obj[i],specialCharList);
}
}else if(obj instanceof Object){
for(var key in obj){
var value = obj[key];
commonConsole(value,"value")
specialCharCheck(value,specialCharList);
// stringHasSpecialCharCheck(value,specialCharList);
}
}else if(typeof(obj) == "string"){
stringHasSpecialCharCheck(obj,specialCharList);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../miniui/scripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="commonJs.js" type="text/javascript"></script>
<script src="../layerTest/layer/layer.js" type="text/javascript"></script>
<script src="../layerTest/layerCommonJs.js" type="text/javascript"></script>
<link rel="stylesheet" href="commonCss.css" type="text/css">
<style>
.errorClass {
background-color: #ff572259;
}
</style>
</head>
<body>
<form id="formId">
<div>
requirelable :
<input id="name" name="name" onchange="onchangeFun()">
</div>
<div>
emaillable :
<input id="email" name="email">
</div>
<div>
numberlable :
<input id="number" name="number">
</div>
<div>
intlable :
<input id="int" name="int">
</div>
<div>
stringlable :
<input id="string" name="string">
</div>
</form>
<button onclick="checkFun()">check</button>
</body>
</html>
<script type="text/javascript">
var dataOptionForName = {
name : {
id : 'name',
name : 'name',
lable : 'requirelable',
required : true
},
email : {
id : 'email',
name : 'email',
lable : 'emaillable',
required : true,
email : true
},
number : {
id : 'number',
name : 'number',
lable : 'numberlable',
required : true,
max : 15.5,
min : 0.5
},
int : {
id : 'int',
name : 'int',
lable : 'intlable',
required : true,
int : true, max : 100, min : 1
},
string : {
id : 'string',
name : 'string',
lable : 'stringlable',
required : true,
maxLen : 15,
minLen : 5
}
}
function validateErrorCallFun(elementId, msg) {
if (msg == '') {
$('#' + elementId).removeClass("errorClass");
} else {
$('#' + elementId).addClass("errorClass");
// openAlert(msg);
// alert(msg);
commonConsole(msg, "msg");
}
// console.info(elementId + " --> " + msg);
}
function checkFun() {
var data = getFormData("formId");
// var datamsg = getFormDataValidateMsgList(data,dataOptionForName,validateErrorCallFun);
var datamsg = getFormDataValidateMsgList(data, dataOptionForName);
commonConsole(datamsg, "datamsg");
}
// $('#' + elementId)
$("#name").change(function () {
console.log("name1111");
})
$("#name").change(function (v1, v2, v3, v4) {
console.log("name222222");
})
function onchangeFun() {
console.log("name3333");
}
$(document).ready(function () {
// formValidateInit(dataOptionForName,validateErrorCallFun);
formValidateInit(dataOptionForName);
});
</script>
//获取数组中的重复元素,返回重复元素数组
function getArrayDuplicate(array) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]]) {
checkResultTmep.push(array[i])
} else {
checkTmep[array[i]] = "true";
}
}
return checkResultTmep;
}
//获取数组中的去重后的元素数组
function getArrayNotDuplicate(array) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]]) {
} else {
checkTmep[array[i]] = "true";
checkResultTmep.push(array[i])
}
}
return checkResultTmep;
}
//获取对象数组中的重复元素,返回重复元素数组
function getObjArrayDuplicate(array, field) {
var checkResultTmep = [];
var checkTmep = {};
for (var i = 0; i < array.length; i++) {
if (checkTmep[array[i]][field]) {
checkResultTmep.push(array[i])
} else {
checkTmep[array[i]] = "true";
}
}
return checkResultTmep;
}
//检查电话号码是否符合要求
function isPhoneNum(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone);
}
//post方式下载文件,params为object
function postDownloadFile(downloadrl, params) {
// 创建form元素
var tempForm = document.createElement("form");
// 设置form属性
tempForm.action = url;
tempForm.target = "_self";
tempForm.method = "post";
tempForm.style.display = "none";
// 处理需要传递的参数
for (var x in params) {
var opt = document.createElement("textarea");
opt.name = x;//参数名
opt.value = params[x]; //参数值
tempForm.appendChild(opt); //
}
document.body.appendChild(temp_form);
// 提交表单
tempForm.submit();
}
//JSON串转Object
function jsonStringToObj(JsonString) {
try {
return JSON.parse(JsonString);
} catch (err) {
alert(err); // 可执行
alert(JsonString); // 可执行
throw err;
}
}
//Object转JSON串
function jsonObjToString(object) {
try {
return JSON.stringify(object);
} catch (err) {
alert(err); // 可执行
alert(JsonString); // 可执行
throw err;
}
}
//通过ID显示元素
function showElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).show();
}
}
//通过ID隐藏元素
function hideElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).hide();
}
}
//通过ID禁用元素
function disabledElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " input";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " button";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " a";
$(idSelect).attr('disabled', true).css("pointer-events", "none");
}
}
//通过ID不禁用元素
function enabledElementsByIds(idArray) {
for (var i = 0; i < idArray.length; i++) {
var idSelect = "#" + idArray[i];
$(idSelect).attr('disabled', false);
idSelect = "#" + idArray[i] + " input";
$(idSelect).attr('disabled', false);
idSelect = "#" + idArray[i] + " button";
$(idSelect).attr('disabled', true);
idSelect = "#" + idArray[i] + " a";
$(idSelect).attr('disabled', false).css("pointer-events", "auto");
}
}
//获取From中的数据object
function getFormData(fromId) {
var formArray = $("#" + fromId).serializeArray();
var formObject = {};
$.each(formArray, function (i, item) {
if (formObject[item.name]) {
formObject[item.name] = formObject[item.name] + "," + item.value;
} else {
formObject[item.name] = item.value;
}
});
return formObject;
}
function setFormData(selector, data) {
if (data) {
for (var key in data) {
var el = $(selector + " [name='" + key + "']");
// commonConsole(el[0],"el[0]")
var value = data[key];
if (el[0].tagName == "SELECT") {
value = value.split(',')
} else if (el[0].tagName == "INPUT" && el[0].type == "checkbox") {
value = value.split(',')
} else if (el[0].tagName == "INPUT" && el[0].type == "radio") {
value = value.split(',')
} else {
value = data[key];
}
// commonConsole(value,"value")
// commonConsole(key,"key")
el.val(value);
}
}
}
//为指定元素加入粘贴事件处理,IE不能在非输入框中触发这个事件
// function addPasteByElement(elementId,onPasteFun) {
// $('#'+elementId ).bind({
// paste: function(e) { //paste事件
// var eve = e.originalEvent
// var cp = eve.clipboardData;
// var data=undefined;
// var clipboardData = window.clipboardData; // IE
// if (!clipboardData) { //chrome
// clipboardData = e.originalEvent.clipboardData
// }
// data = clipboardData.getData('Text');
// if(onPasteFun){
// onPasteFun(data,e.target);
// }
// }
// });
// }
function addPasteByElement(elementId, onPasteFun) {
if (compatibleBrowser()) {
$('#' + elementId).bind({
paste : function (e) { //paste事件
var eve = e.originalEvent
var cp = eve.clipboardData;
var data = undefined;
var clipboardData = window.clipboardData; // IE
if (!clipboardData) { //chrome
clipboardData = e.originalEvent.clipboardData
}
data = clipboardData.getData('Text');
onPasteFun(data, e.target);
}
});
} else {
$('#' + elementId).attr("tabindex", "0");
$('#' + elementId).bind("keydown", function (e) {
if (e.ctrlKey && e.keyCode == 86) { //ctrl + v
// alert("ctrl + v");
// alert(e.target.id);
if (e.target.id == elementId) {
var clipboardData = window.clipboardData; // IE
data = clipboardData.getData('Text');
onPasteFun(data, e.target);
}
}
});
}
}
//粘贴板中excel的内容以行字符串数组返回[]
function getExcelRowStringArray(pasteData) {
var excelData = [];
if (!pasteData) {
return excelDataArray;
}
var newArr = [];
if (typeof pasteData === "string") {
newArr = pasteData.split("\n");
if (newArr.length > 0) {
for (i = 0; i < newArr.length; i++) {
var item = newArr[i];
newArr[i] = item.replace(/\"/g, "").replace(/(^\s*)/g, "")
.replace(/(\s*$)/g, "");
}
excelData = newArr.slice(0, newArr.length - 1);
}
}
return excelData;
}
//粘贴板中excel的内容以行列二维数组返回[][]
function getExcelRowsArray(excelRowStringArray) {
var excelRowsArray = [];
if (!excelRowStringArray) {
return excelRowsArray;
}
for (var i = 0; i < excelRowStringArray.length; i++) {
var item = excelRowStringArray[i];
var strArray = item.split("\t");
excelRowsArray[i] = strArray;
}
return excelRowsArray;
}
//浏览器IE为false,其他为true
function compatibleBrowser() {
var userAgent = window.navigator.userAgent;
if (userAgent.indexOf("Chrome") > -1 || userAgent.indexOf("Firefox") > -1
|| userAgent.indexOf("Opera") > -1) {
return true;
} else {
return false;
}
}
//对象按对应关系转换key
// var fieldMappingObj ={};
// fieldMappingObj.id = 'idNum'; //id转换为idNum
// fieldMappingObj.pid = 'pidNum';
function ObjChangeField(obj, fieldMappingObj) {
if (!obj) {
throw 'obj undefined';
}
if (!fieldMappingObj) {
return obj;
}
var returnObj = {};
for (var key in obj) {
var value = obj[key];
var mapToKey = fieldMappingObj[key];
//有就进行key的更换,没有就按原有key输出
if (mapToKey) {
returnObj[mapToKey] = value;
} else {
returnObj[key] = value;
}
}
return returnObj;
}
//对象数组按对应关系转换key
// var fieldMappingObj ={};
// fieldMappingObj.id = 'idNum'; //id转换为idNum
// fieldMappingObj.pid = 'pidNum';
function ObjListChangeField(objList, fieldMappingObj) {
if (!objList) {
throw 'objList undefined';
}
if (!objList.length) {
throw 'objList length undefined';
}
var returnObjArray = [];
for (var i = 0; i < objList.length; i++) {
var obj = objList[i];
var returnObj = ObjChangeField(obj, fieldMappingObj);
returnObjArray.push(returnObj);
}
return returnObjArray;
}
//对象复制(浅度复制)
function copyObj(obj) {
if (!obj) {
throw 'obj undefined';
}
var returnObj = {};
for (var key in obj) {
var value = obj[key];
returnObj[key] = value;
}
return returnObj;
}
//对象深度复制(深度复制)
function deepClone(obj) {
let newObject;
if (obj === null) {
return null;
}
else if (!(obj instanceof Object)) {
return obj;
}
else if (obj instanceof Date) {
return new Date(obj);
}
else if (obj instanceof Function) {
return Object.assign(obj);
}
else if (obj instanceof RegExp) {
return new RegExp(obj);
}
else if (obj instanceof Array) {
newObject = [];
for (item of
obj
)
{
newObject.push(Object.deepClone(item));
}
}
else {
newObject = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
for (let key of
Object.keys(obj)
)
{
if (newObject[key] != obj) {
newObject[key] = Object.deepClone(obj[key]);
} else {
newObject[key] = newObject;
}
}
}
return newObject;
}
//目录树按key和value进行过滤,返回符合的树结构(childrenKey-->childrenListKey)
function menuTreeFilterByKeyValue(menuList, key, value, childrenKey) {
if (!menuList) {
throw 'menuList undefined';
}
function nodeFillNewFromOld(oldNode, childrenKey) {
var newNode = copyObj(oldNode);
newNode[childrenKey] = undefined;
return newNode;
}
function checkNodeEquals(node, key, value) {
if (!node[key]) {
return false;
}
if (node[key].indexOf(value) != -1) {
return true;
} else {
return false;
}
}
var menuNew = [];
for (var i = 0; i < menuList.length; i++) {
var nodeNew = undefined;
var node = menuList[i];
var childrenNode = node.children;
var childrenMenu = [];
if (childrenNode) {
if (childrenNode.length > 0) {
childrenMenu = menuFilterByKeyValue(childrenNode, key, value, childrenKey);
}
}
if (childrenMenu) {
if (childrenMenu.length > 0) {
nodeNew = new Object();
nodeNew = nodeFillNewFromOld(node, childrenKey);
nodeNew.children = childrenMenu;
} else {
if (checkNodeEquals(node, key, value)) {
nodeNew = new Object();
nodeNew = nodeFillNewFromOld(node, childrenKey);
}
}
}
if (nodeNew) {
menuNew.push(nodeNew);
}
}
return menuNew;
}
//List转换为Tree结构
function listToTree(list, childKey, parentKey, childListKey) {
function listToObjMap(list, key) {
if (!list) {
throw 'list undefined';
}
if (!key) {
throw 'key undefined';
}
var objMap = {};
for (var i = 0; i < list.length; i++) {
var obj = list[i];
var objKey = obj[key];
if (objMap[objKey]) {
objMap[objKey].push(obj);
} else {
objMap[objKey] = [];
objMap[objKey].push(obj);
}
}
return objMap;
}
function listToTreeFor(listTop, childKey, parentMap, childListKey) {
if (!listTop) {
throw 'listTop undefined';
}
if (!childKey) {
throw 'childKey undefined';
}
if (!parentMap) {
throw 'parentMap undefined';
}
var treeObjArray = [];
for (var i = 0; i < listTop.length; i++) {
var obj = listTop[i];
var childKeyValue = obj[childKey];
if (!childKeyValue) {
throw 'childKeyValue undefined';
}
var listTopTemp = parentMap[childKeyValue];
var objTemp = copyObj(obj);
if (listTopTemp) {
var childList = listToTreeFor(listTopTemp, childKey, parentMap, childListKey);
objTemp[childListKey] = childList;
treeObjArray.push(objTemp);
} else {
treeObjArray.push(objTemp);
}
}
return treeObjArray;
}
if (!list) {
throw 'list undefined';
}
if (!childKey) {
throw 'childKey undefined';
}
if (!parentKey) {
throw 'parentKey undefined';
}
if (!childListKey) {
throw 'childListKey undefined';
}
var map = listToObjMap(list, parentKey);
var mapChild = listToObjMap(list, childKey);
//子里面没有的就是顶级元素
var listTopTemp = [];
for (var key in map) {
var objArray = mapChild[key];
if (!objArray) {
// listTopTemp.push(map[key]);
var tempArray = map[key];
if (tempArray.length > 0) {
for (var i = 0; i < tempArray.length; i++) {
listTopTemp.push(tempArray[i])
}
}
// listTopTemp.concat(map[key]);
}
}
if (listTopTemp.length == 0) {
throw 'top list is empty';
}
var treeObj = listToTreeFor(listTopTemp, childKey, map, childListKey);
return treeObj;
}
function getTimestamp(dateTemp) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
return value;
}
function dateAddMs(dateTemp, numMs) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
value += numMs; //将天数转换成毫秒后与开始时间相加得到结束时间的毫秒数
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
return dateTemp2;
}
function dateAddSecond(dateTemp, numSecond) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setSeconds(dateTemp2.getSeconds() + numSecond);
return dateTemp2;
}
function dateAddMinute(dateTemp, numMinute) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setMinutes(dateTemp2.getMinutes() + numMinute);
return dateTemp2;
}
function dateAddHour(dateTemp, numHours) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setHours(dateTemp2.getHours() + numHours);
return dateTemp2;
}
function dateAddDate(dateTemp, numDate) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setDate(dateTemp2.getDate() + numDate);
return dateTemp2;
}
function dateAddYear(dateTemp, numYear) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setYear(dateTemp2.getYear() + numYear);
return dateTemp2;
}
function dateAddMonth(dateTemp, numMonth) {
var value = dateTemp.getTime(); //将开始时间转为毫秒
var dateTemp2 = new Date(value); //将得到的毫秒数转换为日期
dateTemp2.setMonth(dateTemp2.getMonth() + numMonth);
return dateTemp2;
}
//计算地图上的距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
function getMapDistance(lat1, lng1, lat2, lng2) {
function Rad(d) {
return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}
var radLat1 = Rad(lat1);
var radLat2 = Rad(lat2);
var a = radLat1 - radLat2;
var b = Rad(lng1) - Rad(lng2);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137;// EARTH_RADIUS;
s = Math.round(s * 10000) / 10000; //输出为公里
//s=s.toFixed(4);
return s;
}
function convertBase64UrlToBlob(urlData) {
if (!urlData) {
urlData = '';
}
var bytes = urlData; //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {type : 'image/jpg'});
}
//移动端向body输出执行错误信息
function showErrorMsgToBody(msg) {
var temp = $("#commonErrorMsgInfo")[0];
if (!temp) {
$("body").append('<textarea id="commonErrorMsgInfo" style="width: 98%;" rows="30"></textarea>');
}
$("#commonErrorMsgInfo").val(msg); //方法2
}
//替换字符
function replaceAll(srcStr, findStr, replaceStr) {
var temp = srcStr.replace(new RegExp(findStr, 'g'), replaceStr);
return temp;
}
//时间转字符串
//"yyyy-MM-dd hh:mm:ss",yyyy/MM/dd hh:mm:ss
function dateFormat(date, fmt) {
var o = {
"M+" : date.getMonth() + 1, //月份
"d+" : date.getDate(), //日
"h+" : date.getHours(), //小时
"m+" : date.getMinutes(), //分
"s+" : date.getSeconds(), //秒
"q+" : Math.floor((date.getMonth() + 3) / 3), //季度
"S" : date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
//获取这的开始时间
function getFirstTimeOfDate(date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取这周的周一
function getFirstDayOfWeek(date) {
var weekday = date.getDay() || 7; //获取星期几,getDay()返回值是 0(周日) 到 6(周六) 之间的一个整数。0||7为7,即weekday的值为1-7
date.setDate(date.getDate() - weekday + 1);//往前算(weekday-1)天,年份、月份会自动变化
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当月第一天
function getFirstDayOfMonth(date) {
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当季第一天
function getFirstDayOfSeason(date) {
var month = date.getMonth();
if (month < 3) {
date.setMonth(0);
} else if (2 < month && month < 6) {
date.setMonth(3);
} else if (5 < month && month < 9) {
date.setMonth(6);
} else if (8 < month && month < 11) {
date.setMonth(9);
}
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
//获取当年第一天
function getFirstDayOfYear(date) {
date.setMonth(0);
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
////该月第一个周几的日期(1-7)
//function getFirstWeekdayOfMonday(year, month, weekday){
// var date = new Date();
// // 该月第一天
// date.setFullYear(year);
// date.setMonth(month);
// date.setDate(1);
// date.setHours(0);
// date.setMinutes(0);
// date.setSeconds(0);
// date.setMilliseconds(0);
// var w1 = date.getDay();
// if (w1 == 0) {
// w1 = 7;
// }
// var addDate=0;
// if(weekday>=w1){
// addDate = weekday - w1
// }else{
// addDate = 7+weekday - w1;
// }
// date.setDate(date.getDate() + addDate);
// return date;
//}
////该月第一个周几的日期(1-7)
function getFirstWeekdayOfMonday(dateTemp, weekday) {
var date = new Date();
// 该月第一天
date.setFullYear(dateTemp.getFullYear());
date.setMonth(dateTemp.getMonth());
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var w1 = date.getDay();
if (w1 == 0) {
w1 = 7;
}
var addDate = 0;
if (weekday >= w1) {
addDate = weekday - w1
} else {
addDate = 7 + weekday - w1;
}
date.setDate(date.getDate() + addDate);
return date;
}
//读取文件DataURL
function readImageFileAsDataURL(file, onloadFun) {
var fileReader = new FileReader();//创建new FileReader()对象
var imgObj = file;//获取图片
fileReader.readAsDataURL(imgObj);//将图片读取为DataURL
fileReader.onload = function (e) {
if (onloadFun) {
onloadFun(e)
}
};
}
//进入调试模式
$(function () {
$('body').append(
'<div style="width: 100%;height: 25px;background-color: #fffff8" onclick="debugKeyClickFun()"></div>');
});
var debugKeyTimeOutEvent = 0;
var debugKeyTimeNums = 0;
function debugKeyClickPressFun() {
console.info("debugKeyTimeNums ==" + debugKeyTimeNums);
if (debugKeyTimeNums >= 10) {
console.info("长按事件触发发");
erudaDebugEnterFun();
}
debugKeyTimeNums = 0;
debugKeyTimeOutEvent = 0;
}
function debugKeyClickFun() {
console.info("debugKeyClickFun");
if (debugKeyTimeOutEvent == 0) {
debugKeyTimeOutEvent = setTimeout("debugKeyClickPressFun()", 5000);
debugKeyTimeNums = debugKeyTimeNums + 1;
} else {
debugKeyTimeNums = debugKeyTimeNums + 1;
}
}
var erudaDebugTest = 0;
function erudaDebugEnterFun() {
if (erudaDebugTest == 0) {
erudaDebugTest = 1;
var script = document.createElement('script');
script.src = "http://eruda.liriliri.io/eruda.min.js";
document.body.appendChild(script);
script.onload = function () {
eruda.init();
}
}
}
//进行图片压缩(返回base64),rate压缩比(0.8),completeFun(data)压缩完回调
function compressImageData(srcData, quality, completeFun) {
var image = new Image();
image.src = srcData;
image.onload = function () {
var expectWidth = this.naturalWidth;
var expectHeight = this.naturalHeight;
if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 1000) {
expectWidth = 1000;
expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
} else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1400) {
expectHeight = 1400;
expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = expectWidth;
canvas.height = expectHeight;
ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
var dataReturn = canvas.toDataURL("image/jpeg", quality);
if (completeFun) {
completeFun(dataReturn)
}
};
}
//元素是否隐藏
function elementIsHide(selector) {
var temp = $(selector).is(":hidden");
return temp;
}
//元素是否显示
function elementIsShow(selector) {
var temp = $(selector).is(":visible");
return temp;
}
//Debug格式输出
function logDebug(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
//Info格式输出
function logInfo(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
function commonConsole(logdata, showName) {
if (showName) {
console.log(showName + " :-----------------");
}
console.log(logdata);
console.log("");
}
//获取HTML的STRING
function elementToString(selector) {
var temp = $(selector).prop("outerHTML");
return temp;
}
//获取Iframe的运行环境,用以运行其内的相关函数
function getIframeContentWindow(iframe) {
return iframe.contentWindow;
}
//用一个对象中的值赋给另一个对象(按字段名进行)
function objSetObjByField(srcObj, targetObj) {
if (!srcObj) {
throw 'srcObj undefined';
}
if (!targetObj) {
throw 'targetObj undefined';
}
for (var key in srcObj) {
if (key in targetObj) {
targetObj[key] = srcObj[key];
}
}
return targetObj;
}
//检验电话号码
function checkPhone(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone.trim());
}
//检验身份证号码
function checkPeopleCard(cardNum) {
var reg = /^[\d]{17}[0-9|X|x]{1}$/;
return reg.test(cardNum.trim());
}
//邮政编码号码
function checkPostcode(cardNum) {
var reg = /^[\d]{6}/;
return reg.test(cardNum.trim());
}
//设置属性值
function setAttrValue(selector, attribute, value) {
$(selector).attr(attribute, value);
}
//获取属性值
function getAttrValue(selector, attribute) {
return (selector).attr(attribute);
}
//hasAttr
function hasAttr(selector, attribute) {
if (typeof ($(selector).attr(attribute)) == "undefined") {
return false;
} else {
return true;
}
}
//addClass
function addClass(selector, clazz) {
return $(selector).addClass(clazz);
}
//removeClass
function removeClass(selector, clazz) {
return $(selector).removeClass(clazz);
}
//是否包含指定的 class
function hasClass(selector, clazz) {
return $(selector).hasClass(clazz);
}
//是否是num
function isNumber(value) {
var reg = (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/);
var flag = reg.test((value + '').trim());
return flag;
}
//是否是整数
function isInt(value) {
var reg = /^-?\d+$/;
var flag = reg.test((value + '').trim());
return flag;
}
//检验电话号码
function isPhone(phone) {
var reg = /^1[3|4|5|7|8|9|6]\d{9}$/;
return reg.test(phone.trim());
}
//检验身份证号码
function isPeopleCard(cardNum) {
var reg = /^[\d]{17}[0-9|X|x]{1}$/;
return reg.test(cardNum.trim());
}
//检验邮箱地址号码
function isEmail(emailNum) {
var reg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
return reg.test(emailNum.trim());
}
//对象里的内容前后去空格(trim)
function objTrim(obj) {
if (obj) {
for (var key in obj) {
obj[key] = obj[key].trim();
}
}
return obj;
}
//数字范围检测
function numberRangeCheck(val, minVal, maxVal) {
var flag = isNumber(val);
if (!flag) {
throw val + "不是数字";
}
if (minVal != null && minVal != undefined) {
var flag = isNumber(minVal);
if (!flag) {
throw "最小值:" + minVal + "不是数字";
}
if (val < minVal) {
throw val + " < " + minVal + ",小于最小值:" + minVal;
}
}
if (maxVal != null && maxVal != undefined) {
var flag = isNumber(maxVal);
if (!flag) {
throw "最大值:" + maxVal + "不是数字";
}
if (val > maxVal) {
throw val + " > " + maxVal + ",大于最大值:" + maxVal;
}
}
}
//字符长度检测
function stringLenCheck(val, minLen, maxLen) {
if (val == null || val == undefined) {
throw "值为:" + val + ",不为字符串";
}
val = val.trim();
if (minLen != null && minLen != undefined) {
var flag = isInt(minLen);
if (!flag) {
throw "最小长度:" + minLen + "不是数字";
}
if (val.length < minLen) {
throw val + " 长度 < 最小长度 " + minLen;
}
}
if (maxLen != null && maxLen != undefined) {
var flag = isInt(maxLen);
if (!flag) {
throw "最大长度:" + maxLen + "不是数字";
}
if (val.length > maxLen) {
throw val + " 长度 > 最大长度 " + maxLen;
}
}
}
//字符串不为空检测
function requiredCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",为空字符串";
}
}
//int检测
function intCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",不为整数";
}
var flag = isInt(val);
if (!flag) {
throw val + "不是整数";
}
}
//email检测
function emailCheck(val) {
if (val != null && val != undefined) {
var flag = isEmail(val);
if (!flag) {
throw val + "不是正确的电子邮件地址";
}
}
}
//number检测
function numberCheck(val) {
if (val === null || val === undefined || val.trim() === "") {
throw "值为:" + val + ",不为数字";
}
var flag = isNumber(val);
if (!flag) {
throw val + "不是数字";
}
}
//数据校验
//dataOption={id:id,required:}
function valValidateCheck(val, dataOption, validateCallFun) {
//dataOption中那些key要校验的
var validateKey = {
required : true,
email : true,
url : true,
number : true,
int : true,
maxLen : true,
minLen : true,
range : true,
max : true,
min : true
}
var defaultDataOptionMsg = {
required : "这是必填字段",
email : "请输入有效的电子邮件地址",
url : "请输入有效的网址",
number : "请输入有效的数字",
int : "请输入整数",
maxLen : "字符串长度应小于设置值",
minLen : "字符串长度应大于设置值",
max : "数值应小于设置值",
min : "数值应大于设置值",
}
if (dataOption) {
for (var key in dataOption) {
var checkFlag = validateKey[key];
// logDebug(checkFlag, "checkFlag");
if (!checkFlag) {
continue;
}
//
try {
if (key == "required") {
requiredCheck(val);
} else if (key == "email") {
emailCheck(val);
} else if (key == "number") {
numberCheck(val)
} else if (key == "int") {
intCheck(val)
} else if (key == "maxLen" || key == "minLen") {
var minLen = dataOption['minLen'];
var maxLen = dataOption['maxLen'];
stringLenCheck(val, minLen, maxLen);
} else if (key == "max" || key == "min") {
var minVal = dataOption['min'];
var maxVal = dataOption['max'];
numberRangeCheck(val, minVal, maxVal);
} else if (key == "url") {
//numberCheck(val)
}
//用于
var msg = "";
var elementId = dataOption['id'];
if (validateCallFun) {
validateCallFun(elementId, msg);
} else {
defaultValidateCallFun(elementId, msg);
}
} catch (err) {
var msg = defaultDataOptionMsg[key];
var lable = dataOption['lable'];
var elementId = dataOption['id'];
if (lable) {
msg = '字段名:' + lable + ",\n" + err + ',\n 设置要求:' + msg;
}
if (validateCallFun) {
validateCallFun(elementId, msg);
} else {
defaultValidateCallFun(elementId, msg);
}
throw msg;
}
}
}
}
//数据校验默认处理
function defaultValidateCallFun(elementId, msg) {
if(msg==''){
$('#' + elementId).removeClass("validateErrorShow");
}else{
$('#' + elementId).addClass("validateErrorShow");
// openAlert(msg);
// alert(msg);
commonConsole(msg,"msg");
}
}
//from数据校验Init
function formValidateInit(dataOptionForName, validateCallFun) {
if (dataOptionForName) {
if (!validateCallFun) {
validateCallFun = defaultValidateCallFun();
}
for (var key in dataOptionForName) {
var dataOption = dataOptionForName[key];
if (!dataOption) {
continue;
}
var id = dataOption["id"];
if (!id) {
continue;
}
var temp = $('#' + id);
if (!temp) {
continue;
}
var changeFun = (function (id, dataOption, validateCallFun) {
return function () {
var val = $('#' + id).val();
try {
valValidateCheck(val, dataOption, validateCallFun);
} catch (err) {
openAlert(err);
}
// valValidateCheck(val, dataOption, validateCallFun);
}
})(id, dataOption, validateCallFun);
temp.change(changeFun); //值改变事件
temp.blur(changeFun);//失去焦点事件
// commonConsole(changeFun,'changeFun');
}
}
}
//from数据校验
function getFormDataValidateMsgList(data, dataOptionForName, validateCallFun) {
var validateMsgList = [];
if (data) {
for (var key in data) {
var dataOption = dataOptionForName[key];
if (dataOption) {
var val = data[key];
try {
valValidateCheck(val, dataOption, validateCallFun);
} catch (err) {
var lable = dataOption['lable'];
var id = dataOption['id'];
var name = dataOption['name'];
var msg = err;
var obj = {
id : id,
lable : lable,
name : name,
msg : msg,
dataOption : dataOption
}
validateMsgList.push(obj);
}
}
}
}
return validateMsgList;
}
//获取非空字符串
function getNotEmptyString(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return "";
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return "";
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//获取非空数字(如果是字符串返字符串)
function getNotEmptyNum(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//treeToList
function treeToList(obj, defaultValue) {
if (obj === undefined || obj === null) {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
var temp = (obj + "").replace(/^\s+|\s+$/gm, '');
if (temp === "") {
if (defaultValue === undefined) {
return 0;
} else {
return defaultValue;
}
} else {
return temp;
}
}
}
//向array加入array
function listAddList(toList, addList) {
for (var i = 0; i < addList.length; i++) {
toList.push(addList[i]);
}
return toList;
}
//var test = treeToList(data,"id","pId","child","text","text2","0","");
//树数据转平面数据,文字有层次表示
function treeToList(treeList, childKey, parentKey, childListKey, textKey, textJoinKey, parentValue, parentTextJoinValue) {
var listReturn = [];
var list = treeList;
for (var i = 0; i < list.length; i++) {
var obj = list[i];
// var childKeyTemp = obj[childKey];
var parentValueTemp = obj[childKey];
var parentTextJoinValueTemp = "";
if (parentTextJoinValue == "") {
parentTextJoinValueTemp = obj[textKey];
} else {
parentTextJoinValueTemp = parentTextJoinValue + "->" + obj[textKey];
}
// var parentTextJoinValueTemp = parentTextJoinValue +"->"+ obj[textKey];
var childList = obj[childListKey];
if (childList) {
var listReturnTemp = treeToList(childList, childKey, parentKey, childListKey, textKey, textJoinKey, parentValueTemp, parentTextJoinValueTemp);
listReturn = listAddList(listReturn, listReturnTemp);
}
obj[parentKey] = parentValue;
obj[textJoinKey] = parentTextJoinValueTemp;
listReturn.push(obj);
}
return listReturn;
}
//post提交下载附件
function requestPost(url, parameters) {
var _form = $("<form>");
_form.attr("style", "display:none");
_form.attr("method", "post");
_form.attr("action", url);
$("body").append(_form);
for (var i = 0; i < parameters.length; i++) {
var obj = parameters[i];
var _input = $("<input>");
_input.attr("type", "hidden");
_input.attr("name", obj.name);
_input.attr("value", obj.value);
_form.append(_input);
}
_form.submit();
}
//是否禁用控件
function elementEnabled(elementId, enabledFlag) {
mini.get(elementId).setEnabled(enabledFlag);
}
//是否显示控件
function elementShow(elementId, enabledFlag) {
mini.get(elementId).setVisible(enabledFlag);
}
//是否允许文本输入
function elementAllowInput(elementId, enabledFlag) {
mini.get(elementId).setAllowInput(enabledFlag);
}
//数字转货币形式(参数:数字,保留小数位数,货币符号,整数部分千位分隔符,小数分隔符)
// formatMoney(158479.234, 2, "¥ ", ",", ".")
function formatMoney(number, places, symbol, thousand, decimal) {
number = number || 0;
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return symbol + negative + (j ? i.substr(0, j) + thousand : "") +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" +
thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}
//处理Textarea的字符串
function dealTextareaString(str) {
return str.replace(/\n/g, '\\n').replace(/\r\\n/g, '\\n');
}
//select2Make
function select2Make(selector, dataArry) {
//选择列表初始数据
$(selector).select2({
data : dataArry
});
}
//setSelect2
function setSelect2(selecto, idArray) {
$(selector).val(idArray).trigger('change'); //设置值
}
////判断是否图片类型
function isImageType(file) {
var pictype = file.type;
var type = pictype.split("/")[1];//判断是否图片类型
if (type === "bmp" || type === "tiff" || type === "gif" || type === "jpeg" ||
type === "exif" || type === "png" || type === "raw" || type === "jpg") {
return true;
} else {
return false;
}
}
function commonConsole(data, dataStr) {
console.info("==================== " + dataStr);
console.info(data);
console.info("-------------------- ");
}
//指定特殊字符检测
//var value2 = {
// name:'name',
// arr:[{
// name2:'name2?'
// }],
// sex:15
//}
//
//var specialCharList = ['"','?'];
//
//specialCharCheck(value2,specialCharList);
function stringHasSpecialCharCheck(value,specialCharList){
if(!value){
return;
}
if(typeof(value) == "string" ){
if(specialCharList){
for(var i=0;i<specialCharList.length;i++){
var char = specialCharList[i];
if(value.indexOf(char)>=0){
throw "\"" + value + "\"包含有\"" + char + "\"字符";
}
}
}
}
}
function specialCharCheck(obj,specialCharList){
if(!obj){
return;
}
if(obj instanceof Array){
for(var i=0;i<obj.length;i++){
specialCharCheck(obj[i],specialCharList);
}
}else if(obj instanceof Object){
for(var key in obj){
var value = obj[key];
commonConsole(value,"value")
specialCharCheck(value,specialCharList);
// stringHasSpecialCharCheck(value,specialCharList);
}
}else if(typeof(obj) == "string"){
stringHasSpecialCharCheck(obj,specialCharList);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../miniui/scripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="commonJs.js" type="text/javascript"></script>
<script src="../layerTest/layer/layer.js" type="text/javascript"></script>
<script src="../layerTest/layerCommonJs.js" type="text/javascript"></script>
<link rel="stylesheet" href="commonCss.css" type="text/css">
<style>
.errorClass {
background-color: #ff572259;
}
</style>
</head>
<body>
<form id="formId">
<div>
requirelable :
<input id="name" name="name" onchange="onchangeFun()">
</div>
<div>
emaillable :
<input id="email" name="email">
</div>
<div>
numberlable :
<input id="number" name="number">
</div>
<div>
intlable :
<input id="int" name="int">
</div>
<div>
stringlable :
<input id="string" name="string">
</div>
</form>
<button onclick="checkFun()">check</button>
</body>
</html>
<script type="text/javascript">
var dataOptionForName = {
name : {
id : 'name',
name : 'name',
lable : 'requirelable',
required : true
},
email : {
id : 'email',
name : 'email',
lable : 'emaillable',
required : true,
email : true
},
number : {
id : 'number',
name : 'number',
lable : 'numberlable',
required : true,
max : 15.5,
min : 0.5
},
int : {
id : 'int',
name : 'int',
lable : 'intlable',
required : true,
int : true, max : 100, min : 1
},
string : {
id : 'string',
name : 'string',
lable : 'stringlable',
required : true,
maxLen : 15,
minLen : 5
}
}
function validateErrorCallFun(elementId, msg) {
if (msg == '') {
$('#' + elementId).removeClass("errorClass");
} else {
$('#' + elementId).addClass("errorClass");
// openAlert(msg);
// alert(msg);
commonConsole(msg, "msg");
}
// console.info(elementId + " --> " + msg);
}
function checkFun() {
var data = getFormData("formId");
// var datamsg = getFormDataValidateMsgList(data,dataOptionForName,validateErrorCallFun);
var datamsg = getFormDataValidateMsgList(data, dataOptionForName);
commonConsole(datamsg, "datamsg");
}
// $('#' + elementId)
$("#name").change(function () {
console.log("name1111");
})
$("#name").change(function (v1, v2, v3, v4) {
console.log("name222222");
})
function onchangeFun() {
console.log("name3333");
}
$(document).ready(function () {
// formValidateInit(dataOptionForName,validateErrorCallFun);
formValidateInit(dataOptionForName);
});
</script>
发表评论
-
定时调用函数功能实现
2021-06-11 10:26 1105<html> <head> & ... -
uniApiJs
2021-06-08 18:04 0//获取当前的地理位置、速度 function getLoca ... -
百度人脸识别
2021-05-21 16:11 363package com.gaojinsoft.htwy.y20 ... -
点击DIV触发上传文件的方法
2021-05-20 14:11 1198<div Style="float:left ... -
前端格式化工具与检测工具选择与使用
2021-05-10 20:26 722//工具安装前的准备与 ... -
indexedDb TEST
2021-03-24 08:36 507<!DOCTYPE html> <html& ... -
defineProperty Array push 监听
2020-10-31 15:16 464<!DOCTYPE html> <html ... -
weuiJsLayer.js
2020-07-24 09:56 264var weuiJsAlterMap = {}; f ... -
dataViewCommonJs
2020-05-09 17:00 357// var _elementIdToDataMap={} ... -
editorconfig配置
2020-03-28 20:36 462# https://editorconfig.org root ... -
setFormData
2019-12-20 22:30 0function setFormData(selector,d ... -
高德地图获取地址
2019-09-11 14:42 502高德帐号 135704744 <!doctype ... -
前端实现从剪贴板中获取数据
2019-05-16 14:01 1470//绑定在了body上,也可以绑定在其他可用元素行,但是不是所 ... -
js prototype原理与使用
2018-08-14 15:59 771js prototype原理与使用 prototype 使您 ... -
JS过滤树数据
2018-07-02 16:45 1018<!DOCTYPE html> <html ... -
javascript匿名函数与闭包
2016-09-27 14:10 430javascript匿名函数与闭包 ... -
JavaScript 作用域和作用域链
2016-09-27 09:08 518JavaScript 作用域和作用域链 JavaScrip ... -
Javascript函数
2016-09-28 15:00 501Javascript函数 定义函数 使用function关 ... -
Javascript执行步骤与顺序
2016-09-26 01:09 409Javascript执行步骤与顺序 1.JavaScript ... -
URI和URL的区别、URL编码
2016-09-05 11:47 566URI和URL的区别 URI,是uniform resourc ...
相关推荐
本篇文章将深入探讨Babel 7中的转换插件,特别是如何使用`babel-plugin-transform-commonjs`将CommonJS转换为ESM。 首先,让我们了解CommonJS和ESM的区别。CommonJS采用同步导入机制,允许在代码中使用`require()`...
CommonJS是一种在服务器端JavaScript中实现模块化的规范,它的出现主要是为了标准化服务器端JavaScript模块的加载机制。CommonJS规范最初于2009年提出,它的设计理念是基于同步加载机制,并且以文件为模块的载体。在...
rollup-plugin-commonjs, 将CommonJS模块转换为 ES2015 rollup-plugin-commonjs 将CommonJS模块转换为 ES6,以便它们可以包含在Rollup包中安装npm install --save-dev rollup-plugin-commonjs用法
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
#### 一、CommonJS **CommonJS** 是为了解决JavaScript在实际应用中缺乏模块化支持的问题而诞生的一种规范。它最初是为了让JavaScript能够在服务器端运行,尤其是为了适应Node.js这样的环境。CommonJS的出现极大地...
commonjs-everywhere, 具有别名,可扩展性和源映射的CommonJS浏览器 bundler 到处都是 web浏览器使用从缩小的JS包到原始源的源代码,浏览器替代的别名和任意语言支持的可扩展性。安装npm install -g commonjs-...
nashorn-commonjs-modules, CommonJS的模块支持 Nashorn CommonJS模块支持 Nashorn这个库增加了对CommonJS模块( aka require ) inside的支持( Nashorn脚本引擎) 。 它基于 NodeJS模块的规范,它支持从文件夹加载模块...
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
扩展的EXTJS公共类,扩展的EXTJS公共类,扩展的EXTJS公共类
### CommonJS与ES6模块的区别详解 #### 一、引言 随着JavaScript的发展与应用领域的扩展,特别是Node.js的出现,让JavaScript不仅局限于浏览器环境,更拓展到了服务器端。为了更好地管理和组织代码,模块化成为了...
内容概要:本文详细介绍了JavaScript的模块化编程及其在CommonJS中的实现方法。首先解释了模块化编程的重要性和在JavaScript中的应用,接着具体讲述了CommonJS的规范和实现细节,包括模块的定义、导出、导入及缓存...
CommonJS是Node.js中实现模块化开发的重要规范,它允许我们在JavaScript中导入和导出模块,使得代码结构清晰、可复用性增强。本文将深入探讨CommonJS的基本概念、使用方法以及通过一个模拟扑克牌发牌的小例子来实践...
然后详细对比并解释了 CommonJS 和 ES6 模块的关键概念、语法规则以及各自的特点和区别。其中包括加载方式、静态分析支持程度等方面。此外,文章探讨了这两种标准的实际应用场景及其各自的最佳实践,展示了如何利用...
### JavaScript:模块化编程与CommonJS教程 #### 一、模块化编程简介 ##### 1.1 模块化编程的重要性 在JavaScript开发过程中,随着项目的不断扩大,代码组织和管理面临着越来越大的挑战。传统的单一文件编写方式...
CommonJS 是一种 JavaScript 模块化规范,旨在弥补 JavaScript 原生缺乏标准库的不足。这一规范使得 JavaScript 不仅能用于浏览器端的应用开发,还能应用于服务器端、命令行工具和桌面应用程序等领域。Node.js 是对 ...
无编译无服务器实现浏览器的CommonJS模块化是一种在浏览器环境中直接运行CommonJS规范的模块化方法,无需借助像Webpack或Rollup这样的打包工具。CommonJS是Node.js中广泛使用的模块化规范,允许通过`require()`函数...