简介

ejq是一款非常小巧的JS工具库,未压缩才50K,在jquery的基础上对jquery缺失部分作了很好的弥补作用。

优点:

1、具有内置的模板解析引擎语法和angularjs相近减少学习成本

2、能够方便的对JSON操作,增删查改

3、随机数功能比较健全

4、丰富的通用函数,这些函数是通过N多项目需求并且积累下来的,实用性很强。

功能介绍

一、随机数

       var num= $.random.getNum(10);//获取0-10之间的随机数字
var num2 = $.random.getNumBetween(100,200);//获取100-200之间的随机数字
var num3 = $.random.getNumBetweenLength(4, 5);//获取长度为4-5的随机数字
var num4 = $.random.getNumByLength(10); //获取长度为10的随机数 var w1 = $.random.getWord(10);//获取10位长度的随机(字母加数字)
var w2 = $.random.getNumBetweenLength(2, 4);//获取2位长度到4位长度之间的随机(字母加数字) var guid = $.random.getGuid();//获取guid

二、对JSON的操作

        var json = [{ id: 1, name: "张三" }, { id: 2, name: "李四" }, { id: 3, name: "王五" }];

        //对json进行筛选获取1和2的json集合
var json1And2 = $.linq.where(json, function (v) { return v.id == 1 || v.id == 2; }); //获取id为1的对象
var zs = $.linq.single(json, function (v) { return v.id == 1; }); //获取id>1的第一个对象
var list = $.linq.first(json, function (v) { return v.id > 1; }); //排序
var json2 = $.linq.order(json, "id", "desc"); //移除id为1的对象
$.linq.remove(json, function (v) { v.id == 1; }); //是否存在ID为1的对象,因为让删了当然反回false
var isAnyOne = $.linq.any(json, function (v) { v.id == 1 });

三、数据的双向绑定

第一眼看去像是angularjs,其实是ejq.js模仿angularjs自已实现的模版解析引擎,因为这个功能才写了2天,有很多功能还没来的急实现,会最在近一个月让它更加的健全。

现在已经实现了 异步和同步的数据绑定功能 ,暂不支持运算符和逻辑条件,只作数据绑定还是够用了。

  $(function () {

            //申明模版引擎的作用域
var model = $ejqApp.module("ng-app");
//控制器操作
model.controller("ctr1", function ($scope, $http, $con, $app, $tool, $event) { $scope.model = {
title: "哈哈",
list: [{ id: 1, name: "table1" }, { id: 2, name: "table2" }, { id: 3, name: "table3" }],
item: [{ id: 3, name: "table3" }, { id: 2, name: "table2" }, { id: 1, name: "table1" }],
id: 1
};
$scope.haha = { text: "haha " }; //使用ajax
$http.jsonList = {
url:"../json.json",//随机URL
type: "get",
}; //获取当前控制器
var thObj = $con.getObj();
//获取当前App
var appObj = $app.getObj(); //给当前控制器name注册事件实现双向绑定
appObj.on("click", thObj.find("#name"), function () { //更新model.Title
$scope.model.title ="哈哈"+ $.random.getNumBetweenLength(8, 10); //更换AJAX URL
if ($http.jsonList.url == "../json.json") {
$http.jsonList.url = "../jsonList.json";
} else {
$http.jsonList.url = "../json.json";
} //重新绑定
$ejqApp.apps.bind() alert("数据重新绑定成功")
}) })
$ejqApp.apps.bind();
})
<body ng-app="ng-app">
<h1>
模仿angular.js双向绑定的DEMO
</h1>
<div ng-controller="ctr1">
<input id="name" type="button" value="Reset" />
<div>
<h1>$scope.model</h1>
{{model.title}}
{{model.id}}
<table ng-repeat="item in model.list">
<tr><td>{{item.id}}</td><td>{{item.name}}</td></tr> </table>
<table ng-repeat="item in model.item">
<tr><td>{{item.id}}</td><td>{{item.name}}</td></tr> </table>
</div>
<h1>$scope.haha</h1>
{{haha.text}} <h3>异步加载</h3>
<table ng-repeat="item in jsonList">
<tr><td>{{item.desc}}</td><td>{{item.name}}</td></tr> </table> </div> </body>

HTML

四、常用函数

             //这个函数在写通用框架时比较好用
var kvs = $.action.jsonDictionary({ id: 1, name: "张三" })//将json 转成[{key:id,value:1},{key:name:value:"张三"}] //替换所有a(js中Replace只能替换一个比较2)
$.action.replaceAll("abcdabc", "a", "-") //检测元素是否存在,当存在时执行回调函数,超时会自动停止检测
$.action.elementNullComplate("#id", function () { }); //循环执行检测选择器的元素是否有值,有则执行回调函数过,超过停止检测
$.action.elementValueReady("#id", function () { })
//让setTimeout可以指定执行的次数
$.action.setTimeoutWidthNum(function () { }, 1000, 3);//1秒执行一次,第三次将停止 //去掉最后一个字符
$.action.trimEnd("adfaf,", ","); //指定位置插入字符
$.action.insertStr("adfaf", 2, "2"); //.NET MVC URL处理(可以有效的防止虚拟目录JS跳转URL错误)
//layout.cshtml定义一个hidden <input id='hid' value="@Url.Content("~/")">
$.action.url("/actionName/", "hid", "controllerName", "areaName") //生成的url如下 /xxx/areaName/controllerName/actionName
$.action.url("/actionName/", "hid", "controllerName")
$.action.url("/actionName/", "hid") //更多
//$.action.htmlDecode
//$.action.htmlEncode

五、转换和验证

用法很简单 $.convert.xxx  、$.ValiData.xxx 和 $.valiType.xxx

六、浏览器相关操作

用法也很简单,用法如下:

$.request.queryString().id

$.response.open("/home.index",{id:1})

$.brovali.isIE()

七、通用扩展函数

        //拼接字符串1
var str = "我是中国{0},你是哪国{0}".ejq_format("人");
str = str.ejq_appendFormat(",它是哪国的{0}", "猫"); //拼接字符串2
var str2 = "我是中国{p},你是哪国{p}".ejq_format({p:"人"});
str2 = str2.ejq_appendFormat(",它是哪国的{cat}", { cat: "猫" }); var idObj = "#id".ejq_selector(); //相当于$("#id") var num = 1.2600.ejq_toFixed(2);//四舍五入取2位,和原生toFixed不一样

还有一些功能就不一一的说明了

GIT地址:

https://github.com/sunkaixuan/-common-jquery-ejq.js

源码

/*!
* jQuery Library v2.1
* 说明:Jquery通用库
* 创建时间: sunkaixuan 2014-8-22
* 修改时间:2016-8-2
*/
(function (window, jQuery, undefined) { jQuery.extend({
/*随机值*/
random: {
//获取0-maxNum之间的随机数字
getNum: function (maxNum) {
return $.random.getNumBetween(0, maxNum);
},
//获取min-max之间的随机数字
getNumBetween: function (min, max) {
max = max + 1;
return Math.floor(Math.random() * (max - min)) + min;
},
//获取长度为length的随机数字
getNumByLength: function (length) {
var array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var reval = "";
for (var i = 0; i < length; i++) {
reval += array[$.random.getNumBetween(0, array.length - 1)];
}
return reval
},
//获取长度为minLength-maxLength之间的随机数
getNumBetweenLength: function (minLength, maxLength) {
var length = $.random.getNumBetween(minLength, maxLength);
return $.random.getNumByLength(length);
},
//获取长度wordLength(数字、字母)组成的字符串
getWord: function (wordLength) {
var array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
var reval = "";
for (var i = 0; i < wordLength; i++) {
reval += array[$.random.getNumBetween(0, array.length - 1)];
}
return reval;
},
//获取长度为minLength-maxLength之间的随机(数字、字母)组成的字符串
getWordBetweenLength: function (minLength, maxLength) {
var length = $.random.getNumBetween(minLength, maxLength);
return $.random.getWord(length);
},
getGuid: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}, /*linq*/
linq: {
contains: function (thisVal, cobj) {
if (jQuery.valiData.isEmpty(thisVal)) {
return false;
}
return thisVal.toString().lastIndexOf(cobj.toString()) != -1;
},
/*where*/
where: function (obj, action) {
if (action == null) return;
var reval = new Array();
$(obj).each(function (i, v) {
if (action(v)) {
reval.push(v);
}
})
return reval;
},
single: function (obj, action) {
if (action == null) return;
var reval = null;
$(obj).each(function (i, v) {
if (action(v)) {
reval = (v);
}
})
return reval;
},
remove: function (obj, action) {
var removeItem = $.linq.single(obj, action);
obj.splice(jQuery.inArray(removeItem, obj), 1);
},
/*any*/
any: function (obj, action) {
if (action == null) return;
var reval = false;
$(obj).each(function (i, v) {
if (action(v)) {
reval = true;
return false;
}
})
return reval;
},
/*select*/
select: function (obj, action) {
if (action == null) return;
var reval = new Array();
$(obj).each(function (i, v) {
reval.push(action(v));
});
return reval;
},
/*each*/
each: function (obj, action) {
if (action == null) return;
jQuery(obj).each(function (i, v) {
action(i, v);
});
},
/*first*/
first: function (obj, action) {
if (action == null) return;
var reval = new Array();
$(obj).each(function (i, v) {
if (action(v)) {
reval.push(v);
return false;
}
})
return reval[0];
},
order: function (obj, field, orderByType) {
var p = obj;
p.sort(function down(x, y) {
if (orderByType != null && orderByType.toLocaleLowerCase() == "desc") {
return (x[field] < y[field]) ? 1 : -1;
} else {
return (x[field] > y[field]) ? 1 : -1;
} })
return p;
} }, /*操作*/
action: {
url: function (actionName, hid, controllerName, areaName) {
if (hid == null) {
hid = "HidUrlAction";
}
var isAction = controllerName == null && areaName == null;
var isControllerName = areaName == null && controllerName != null;
var isArea = areaName != null;
var hidValue = $("#" + hid).val();
var regValue = hidValue.match("(^.*)/(.+)/(.+)/$");
var virtualDirectory = regValue[1];
if (isAction) {
return hidValue + actionName;
} else if (isControllerName) {
areaName = regValue[2]
return (virtualDirectory + "/" + areaName + "/" + controllerName + "/" + actionName);
} else if (isArea) {
return (virtualDirectory + "/" + areaName + "/" + controllerName + "/" + actionName);
}
}, //移除最后一个字符
trimEnd: function (str, c) {
var reg = new RegExp(c + "([^" + c + "]*?)$");
return str.replace(reg, function (w) { if (w.length > 1) { return w.substring(1); } else { return ""; } });
},
htmlEncode: function (str) {
return str.replace(/&/g, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
},
htmlDecode: function (str) {
return str.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
},
textEncode: function (str) {
str = str.replace(/&amp;/gi, '&');
str = str.replace(/</g, '&lt;');
str = str.replace(/>/g, '&gt;');
return str;
},
textDecode: function (str) {
str = str.replace(/&amp;/gi, '&');
str = str.replace(/&lt;/gi, '<');
str = str.replace(/&gt;/gi, '>');
return str;
},
//获取json的key和value
jsonDictionary: function (json, key) {
var reval = new Array();
for (key in json) {
reval.push({ key: key, value: json[key] });
}
return reval;
},
insertStr: function (str1, n, str2) {
if (str1.length < n) {
return str1 + str2;
} else {
s1 = str1.substring(0, n);
s2 = str1.substring(n, str1.length);
return s1 + str2 + s2;
}
},
//替换所有字符
replaceAll: function (str, findStr, reStr) {
var reg = new RegExp(findStr, "g");
return str.replace(reg, reStr); },
setTimeoutWidthNum: function (fun, time, number) {
if (fun != null) {
setTimeout(function () {
fun();
number--;
if (number > 0) {
$.action.setTimeoutWidthNum(fun, time, number);
}
}, time)
}
},
//循环执行检测元素值是否有值当有值执行回调函数,超时停止检测
elementValueReady: function (selector, fun, time) {
var selObj = $(selector);
if (time == null) time = 0;
time = time + 50;
if (time > 5000) {//间隔超过5秒则停止检测
return;
}
setTimeout(function () {
var val = "";
try {
val = selObj.val();
} catch (e) { }
var valIsNull = val == null || val == "";
if (valIsNull) {
$.action.elementValueReady(selector, fun, time);
} else {
fun();
}
}, time); },
//循环执行检测选择器的元素如果存在该元素,则执行回调函数过,超过停止检测
elementNullComplate: function (selector, fun, time) {
var selObj = $(selector)
if (time == null) time = 0;
time = time + 50;
if (time > 5000) {//间隔超过5秒则停止检测
return;
}
setTimeout(function () {
if (selObj.size() > 0) {
$.action.elementNullComplate(selector, fun, time);
} else {
fun();
}
}, time); } }, /*日期时间处理*/
getdate: {
//获取当前日期
getPresentDate: function () {
var mydate = new Date();
var str = "" + mydate.getFullYear() + "-";
str += (mydate.getMonth() + 1) + "-";
str += mydate.getDate();
return str;
},
//获取当前日期之前的年月date为日期"2016-6",number>0&<11月数 -leo
//例:getfirsthalf("2016-06",5) 返回半年内的年月数组
getfirsthalf: function (date, number) {
var d = new Date(date.replace(/[^\d]/g, "/") + "/1");
var result = [date];
for (var i = 0; i < number; i++) {
d.setMonth(d.getMonth() - 1);
var m = d.getMonth() + 1;
m = m < 10 ? "0" + m : m;
result.push(d.getFullYear() + "-" + m);
}
return result;
},
//获取一个月天数 or 最后一天 tpye=Day返回天数 否则返回最后一天日期-leo
getLastDay: function (year, month, dateTpye) {
debugger
var new_year = year; //取当前的年份
var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定)
if (month > 12) //如果当前大于12月,则年份转到下一年
{
new_month -= 12; //月份减
new_year++; //年份增
}
var new_date = new Date(new_year, new_month + 1, 1); //取当年当月中的第一天
var date_count = (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月的天数
var last_date = new Date(new_date.getTime() - 1000 * 60 * 60 * 24);//获得当月最后一天的日期
if (dateTpye == 'dayNum') {
return date_count;
}
else {
return last_date;
}
},
//获取两个时间相差天数-leo
//计算sDate1 - sDate2 得到相差天数 2016-06-18格式
getdatedifference: function (sDate1, sDate2) {
var aDate, oDate1, oDate2, iDays
aDate = sDate1.split("-")
oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2006格式
aDate = sDate2.split("-")
oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
return iDays
},
//比较两个时间大小
checkEndTime: function (startTime, endTime) {
var starttime = String(startTime).replace("-", "/").replace("-", "/")
var start = new Date(starttime);
var endtime = String(endTime).replace("-", "/").replace("-", "/")
var end = new Date(endtime);
if (end < start) {
return "Small";
}
else if (end > start) {
return "large";
}
else {
return "equal";
}
} }, /*转换*/
convert: {
//还原json格式的时间
jsonReductionDate: function (cellval, format) {
try {
if (cellval == "" || cellval == null) return "";
var date = new Date(parseInt(cellval.substr(6)));
if (format == null) {
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
} else {
return $.convert.toDate(date, format);
}
} catch (e) {
return "";
}
},
jsonToStr: function (object) {
var type = typeof object;
if ('object' == type) {
if (Array == object.constructor) type = 'array';
else if (RegExp == object.constructor) type = 'regexp';
else type = 'object';
}
switch (type) {
case 'undefined':
case 'function':
case 'unknown':
return;
break;
case 'function':
case 'boolean':
case 'regexp':
return object.toString();
break;
case 'number':
return isFinite(object) ? object.toString() : 'null';
break;
case 'string':
return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function () {
var a = arguments[0];
return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
}) + '"';
break;
case 'object':
if (object === null) return 'null';
var results = [];
for (var property in object) {
var value = jQuery.convert.jsonToStr(object[property]);
if (value !== undefined) results.push(jQuery.convert.jsonToStr(property) + ':' + value);
}
return '{' + results.join(',') + '}';
break;
case 'array':
var results = [];
for (var i = 0; i < object.length; i++) {
var value = jQuery.convert.jsonToStr(object[i]);
if (value !== undefined) results.push(value);
}
return '[' + results.join(',') + ']';
break;
}
},
strToJson: function (str) {
return jQuery.parseJSON(str);
},
toDate: function (date, format) {
var data = new Date(date);
var o = {
"M+": data.getMonth() + 1, //month
"d+": data.getDate(), //day
"h+": data.getHours(), //hour
// "H+": date.getHours(), //hour
"m+": data.getMinutes(), //minute
"s+": data.getSeconds(), //second
"q+": Math.floor((data.getMonth() + 3) / 3), //quarter
"S": data.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(data.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;
},
toInt: function (par) {
if (par == null || par == NaN || par == "") return 0;
return parseInt(par);
},
toNumber: function (obj, pointNum) {
if ($.valiData.isDecimal(obj)) {
var num = parseFloat(obj) + "";
if (num.lastIndexOf(".") == -1) {
return parseFloat(num);
} else {
var index = num.indexOf(".");
var length = num.length;
if ((length - index - 1) > pointNum) {
return parseFloat(parseFloat(num).toFixed(pointNum));
} else {
return parseFloat(num);
}
}
} else {
return 0;
}
},
toFloat: function (par) {
if (par == null || par == NaN || par == "") return 0;
return parseFloat(par);
},
xmlToJQuery: function (data) {
var xml;
if ($.browser.msie) {// & parseInt($.browser.version) < 9
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
// xml = $(xml).children('nodes'); //这里的nodes为最顶级的节点
} else {
xml = data;
}
return $(xml);
},
//将标准时间转换成时间格式-leo
//day: Thu Aug 22 2013 15:12:00 GMT+0800 (中国标准时间) format: yyyy-MM-dd hh:mm:ss
standardTimeToDateTime: function (day, format) {
var dateTime = new Date(day);
var tostr = function (i) {
return (i < 10 ? '0' : '') + i
};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (item) {
switch (item) {
case 'yyyy':
return tostr(dateTime.getFullYear());
break;
case 'MM':
return tostr(dateTime.getMonth() + 1);
break;
case 'mm':
return tostr(dateTime.getMinutes());
break;
case 'dd':
return tostr(dateTime.getDate());
break;
case 'HH':
return tostr(dateTime.getHours());
break;
case 'ss':
return tostr(dateTime.getSeconds());
break;
}
})
}
}, /*数据验证*/
valiData: {
isEmpty: function (val) { return val == undefined || val == null || val == "" || val.toString() == ""; },
isZero: function (val) { return val == null || val == "" || val == 0 || val == "0"; },
//判断是否为数字
isNumber: function (val) { return (/^\d+$/.test(val)); },
//是否是邮箱
isMail: function (val) { return (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(val)); },
//是否是手机
isMobilePhone: function (val) { return (/\d{11}$/.test(val)); },
//判断是否为负数和整数
isNumberOrNegative: function (val) { return (/^\d+|\-\d+$/.test(val)); },
//金额验证
isMoney: function (val) { return (/^[1-9]d*.d*|0.d*[1-9]d*|\d+$/.test(val)); },
isDecimal: function (val) { return (/^(-?\d+)(\.\d+)?$/.test(val)); } }, /*类型验证*/
valiType: {
isArray: function (obj) { return (typeof obj == 'object') && obj.constructor == Array; },
isString: function (str) { return (typeof str == 'string') && str.constructor == String; },
isDate: function (obj) { return (typeof obj == 'object') && obj.constructor == Date; },
isFunction: function (obj) { return (typeof obj == 'function') && obj.constructor == Function; },
isArrayLike: function (obj) {
if (obj == null || isWindow(obj)) {
return false;
}
var length = "length" in Object(obj) && obj.length; if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
} return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
},
isObject: function (obj) { return (typeof obj == 'object') && obj.constructor == Object; }
}, pageHelper: {
referenceFile: function (url, type) {
$(function () {
var isJs = type == "js";
if (isJs) {
var isAny = $("[src='" + url + "']").size() > 0;
if (!isAny)
$("head").append("<script src='" + url + "' /> ");
}
else {
var isAny = $("[href='" + url + "']").size() > 0;
if (!isAny)
$("head").append("<link href='" + url + "'rel='stylesheet' >");
}
})
}
}, //定位
position: {
//使页面元素上下左右居中
center: function (eleSelector) {
var obj = $(eleSelector);
if (obj.size() > 0) {
obj.each(function () {
var obj = $(this);
var wh = $(window).height();
var ww = $(window).width();
var scrh = $(document).scrollTop();
var objh = obj.height();
var objw = obj.width();
var top = scrh + ((wh - objh) / 2);
var left = ww / 2 - objw / 2;
if (scrh > 0) {
obj.css({ position: "absolute", left: left, top: top });
}
})
}
}
}, //ajax辅助
ajaxhelper: {
error: function (msg, action) {
if (action != null) {
action(msg);
}
try {
console.log(msg);
} catch (e) { }
}
}, /*********************************浏览器操作*********************************/
/*浏览获取操作*/
request: {
queryString: function () {
var s1;
var q = {}
var s = document.location.search.substring(1);
s = s.split("&");
for (var i = 0, l = s.length; i < l; i++) {
s1 = s[i].split("=");
if (s1.length > 1) {
var t = s1[1].replace(/\+/g, " ")
try {
q[s1[0]] = decodeURIComponent(t)
} catch (e) {
q[s1[0]] = unescape(t)
}
}
}
return q;
},
url: function () {
return window.location.href;
},
urlEncode: function (str) {
if (str == null) return "";
var tempstr = str.replace(/\+/g, encodeURI("%2B"));
return tempstr;
},
domain: function () {
return window.location.host;
},
pageName: function () {
var a = location.href;
var b = a.split("/");
var c = b.slice(b.length - 1, b.length).toString(String).split(".");
return c.slice(0, 1);
},
pageFullName: function () {
var strUrl = location.href;
var arrUrl = strUrl.split("/");
var strPage = arrUrl[arrUrl.length - 1];
return strPage;
},
back: function () {
history.go(-1);
},
getCookie: function (cookieName) {
var cookieValue = document.cookie;
var cookieStartAt = cookieValue.indexOf("" + cookieName + "=");
if (cookieStartAt == -1) {
cookieStartAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartAt == -1) {
cookieValue = null;
}
else {
cookieStartAt = cookieValue.indexOf("=", cookieStartAt) + 1;
cookieEndAt = cookieValue.indexOf(";", cookieStartAt);
if (cookieEndAt == -1) {
cookieEndAt = cookieValue.length;
}
cookieValue = unescape(cookieValue.substring(cookieStartAt, cookieEndAt));//解码latin-1
}
return cookieValue;
},
//打印
print: function (id/*需要打印的最外层元素ID*/) {
var el = document.getElementById(id);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0) {
document.body.removeChild(iframe);
}
},
//加入收藏夹
addFavorite: function (surl, stitle) {
try {
window.external.addFavorite(surl, stitle);
} catch (e) {
try {
window.sidebar.addpanel(stitle, surl, "");
} catch (e) {
alert("加入收藏失败,请使用ctrl+d进行添加");
}
}
},
//设为首页
setHome: function (obj, vrl) {
try {
obj.style.behavior = 'url(#default#homepage)';
obj.sethomepage(vrl);
} catch (e) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("此操作被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将[signed.applets.codebase_principal_support]的值设置为'true',双击即可。");
}
} else {
alert("抱歉,您所使用的浏览器无法完成此操作。\n\n您需要手动设置为首页。");
}
}
}
}, /*浏览器请求操作*/
response: {
setCookie: function (name, value, time) {
if (time == null) {
time = 30 * 60 * 1000
}
//设置名称为name,值为value的Cookie
var expdate = new Date(); //初始化时间
expdate.setTime(expdate.getTime() + time); //时间
document.cookie = name + "=" + value + ";expires=" + expdate.toGMTString() + ";path=/"; //即document.cookie= name+"="+value+";path=/"; 时间可以不要,但路径(path)必须要填写,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!~
},
open: function (url, params) {
if (params == null || params == "") {
window.open(url);
} else {
if (jQuery.linq.contains(url.toString(), "?")) {
var rurl = url + "&" + jQuery.param(params);
window.open(rurl);
} else {
var rurl = url + "?" + jQuery.param(params);
window.open(rurl);
}
}
},
//页面跳转
redirect: function (url, params) {
if (params == null || params == "") {
window.location.href = url;
} else {
if (jQuery.linq.contains(url.toString(), "?")) {
var rurl = url + "&" + jQuery.param(params);
window.location.href = rurl;
} else {
var rurl = url + "?" + jQuery.param(params);
window.location.href = rurl;
}
}
} }, /*浏览器判段*/
broVali: {
//jquery1.9以上只需要判段IE
isIE: function () {
if (!!window.ActiveXObject || "ActiveXObject" in window)
return true;
else
return false;
},
//老版本jquery用下面的函数
isIE6: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "6.0")
flag = true;
return flag;
},
isIE7: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "7.0")
flag = true;
return flag;
},
isIE8: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "8.0")
flag = true;
return flag;
},
isIE9: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "9.0")
flag = true;
return flag;
},
isIE10: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "10.0")
flag = true;
return flag;
},
isIE11: function () {
var flag = false;
if ($.browser.msie && $.browser.version == "11.0")
flag = true;
return flag;
},
isMozilla: function () {
var flag = false;
if ($.browser.mozilla)
flag = true;
return flag;
},
isOpera: function () {
var flag = false;
if ($.browser.opera)
flag = true;
return flag;
},
isSafri: function () {
var flag = false;
if ($.browser.safari)
flag = true;
return flag;
},
isMobile: function () {
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var flag = false;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = true; break; }
} return flag;
},
isIPhone: function () {
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
return jQuery.jQueryAny(Agents, function (v) {
return v == "iPhone";
});
},
isAndroid: function () {
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
return jQuery.jQueryAny(Agents, function (v) {
return v == "Android";
});
}
} }); /*********************************模板解析引擎 by 2016-8-2*****************/
$(function () {
//通用正则
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
window.$ejqApp = {};
$ejqApp.apps = [];
function setModule(fn, ctr) {
var pars = [];
var fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function (arg) {
arg.replace(FN_ARG, function (all, underscore, name) {
pars.push({ name: name });
});
});
var queueItem = { controller: ctr, pars: pars };
return queueItem;
}
$ejqApp.module = function (app, obj) {
var apps = $.linq.where($ejqApp.apps, function (v) { return v.appName == app });
var isAny = apps != null && apps.length > 0;
if (isAny) {
return apps[0];
} else {
var reval = {
appName: app,
templateHtml: $("[ ng-app=\"" + app + "\"]").html(),
getObj: function () { return $("[ ng-app=\"" + app + "\"]") },
controller: function (ctr, obj) {
var th = this;
var app = this.getObj();
var ctrObj = app.find("[ng-controller='" + ctr + "']");
var queueItem = setModule(obj, ctrObj);
$.each(queueItem.pars, function (i, v) {
if (v.name == "$con") {
v.getObj = function () {
return th.getObj().find("[ng-controller='" + ctr + "']");
};
}
if (v.name == "$app") {
v.getObj = function (selector) {
return th.getObj();
}
}
if (v.name == "$tool") {
v.method = {}
} if (v.name == "$event") {
v.getObj = function (selector) {
return th.getObj();
}
}
}) obj.apply(new function () { }, queueItem.pars);
queueItem.name = ctr;
this.controllerParas = { pars: queueItem };
}
};
$ejqApp.apps.push(reval);
return reval;
}
}
$ejqApp.apps.bind = function () {
$($ejqApp.apps).each(function (i, v) {
var appObj = v.getObj();
appObj.html(v.templateHtml);
var th = v;
$.each(v.controllerParas, function (i, pars) {
var obj = appObj.find("[ng-controller='" + pars.name + "']");
$.each(pars.pars, function (i, par) {
switch (par.name) {
case "$scope":
$scope(obj, par);
break;
case "$http":
$http(obj, par);
break;
}
})
})
})
}
function $scope(obj, par) {
var kvs = $.action.jsonDictionary(par)
$.each(kvs, function (i, v) {
if (v.key == "name") return;
var isArray = $.valiType.isArray(v);
if (isArray) {
resolveArray(v.key, obj, v.value)
} else {
resolveJson(v.key, obj, v.value)
}
})
}
function $http(obj, par) {
var kvs = $.action.jsonDictionary(par)
var kv = $.linq.single(kvs, function (v) {
return $.valiType.isObject(v.value);
});
if (kv == null) return;
var ajaxSetting = kv.value;
if (ajaxSetting != null) { if (ajaxSetting.cache == null) {
ajaxSetting.cache = false;
}
$.ajax({
url: ajaxSetting.url,
cache: ajaxSetting.cache,
dataType: "json",
type: ajaxSetting.type,
success: function (msg) {
var isArray = $.valiType.isArray(msg);
if (isArray) {
resolveArray(kv.key, obj, msg)
} else { resolveJson(kv.key, obj, msg)
}
if (ajaxSetting.success != null) {
ajaxSetting.success(msg);
} },
error: function (msg) {
if (ajaxSetting.error != null) {
ajaxSetting.error(msg);
}
}
});
}
}
function resolveJson(name, obj, json, prefix) {
if (prefix == null) prefix = "";
var kvs = $.action.jsonDictionary(json)
var dataHtml = obj.data("myng-html");
var innerHtml = obj.html();
if (dataHtml == null) {
innerHtml = obj.html();
} else {
innerHtml = dataHtml;
}
var funs = [];
if (innerHtml != null && innerHtml != "") {
$.each(kvs, function (i, v) {
var isArray = $.valiType.isArray(v.value);
if (isArray) {
funs.push({ name: v.key, obj: obj, value: v.value, prefix: name });
} else {
innerHtml = innerHtml.replace(new RegExp("\{\{" + prefix + name + "\." + v.key + "\}\}"), v.value);
}
})
obj.html(innerHtml);
obj.data("myng-html", innerHtml);
$.each(funs, function (i, v) {
resolveArray(v.name, v.obj, v.value, v.prefix);
})
}
}
function resolveArray(name, obj, json, prefix) {
obj.find("[ng-repeat]").each(function () {
var th = $(this);
var innerTemplate = th.html();
var repeatValue = th.attr("ng-repeat");
prefix = prefix == null ? "" : prefix;
var reg = new RegExp("([a-z,A-Z][0-9,a-z,A-Z]*)\\s+in\\s+" + prefix + "." + name);
if (reg.test(repeatValue)) {
th.html("");
var itemName = repeatValue.match(reg)[1];
$.each(json, function (i, jsonItem) {
var kvs = $.action.jsonDictionary(jsonItem)
var appendItem = innerTemplate;
$.each(kvs, function (i, v) {
var isArray = $.valiType.isArray(v.value);
if (isArray) {
debugger
resolveArray(v.key, obj, v.value, name);
} else {
appendItem = appendItem.replace(new RegExp("\{\{" + itemName + "\." + v.key + "\}\}"), v.value);
}
})
th.append(appendItem);
});
}
})
var dataHtml = obj.data("myng-html", obj.html());
}
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if ($.valiType.isFunction(obj)) {
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if ($.valiType.isArray(obj) || $.valiType.isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
} }) /*********************************form操作*********************************/
jQuery.fn.extend({
//获取元素属性以","隔开
attrToStr: function (attr) {
var reval = "";
this.each(function () {
reval += jQuery(this).attr(attr) + ","
})
reval = jQuery.jQueryAction.trimEnd(reval, ",");
return reval;
},
//清空表单
formClear: function () {
this.find("input:text,select,input:hidden,input:password").each(function () {
$(this).val("");
});
this.find("input:checkbox,input:radio").each(function () {
$(this).removeAttr("checked");
});
},
//将json对象自动填充到表单
//例如 $('form').formFill({data:{id:1},prefix:"user."}) 填充后 <input name='user.id' value='1' >
formFill: function (option) {
var prefix = option.prefix;
if (prefix == undefined) prefix = "";
var frmData = option.data;
for (i in frmData) {
var dataKey = i;
var thisData = this.find("[name='" + prefix + i + "']");
var text = "text";
var hidden = "hidden";
if (thisData != null) {
var thisDataType = thisData.attr("type");
var val = frmData[i];
var isdata = (val != null && val.toString().lastIndexOf("/Date(") != -1);
if (thisDataType == "radio") {
thisData.filter("[value=" + val + "]").attr("checked", "checked")
if (val == true || val == "0") val = "True";
else if (val == false || val != "0") val = "False";
thisData.filter("[value=" + val + "]").not("donbool").attr("checked", "checked")
} else if (thisDataType == "checkbox") {
if (thisData.size() == 1) {
if (val == "true" || val == 1 || val == "True" || val == "1") {
thisData.attr("checked", "checked");
} else {
thisData.removeAttr("checked");
}
} else { thisData.removeAttr("checked");
var cbIndex = i;
if (val.lastIndexOf(",") == -1) {
this.find("[name='" + prefix + dataKey + "'][value='" + prefix + val + "']").attr("checked", "checked");
} else {
jQuery(val.split(',')).each(function (i, v) {
this.find("[name='" + prefix + dataKey + "'][value='" + prefix + v + "']").attr("checked", "checked");;
})
}
} } else {
if (isdata) {
val = jQuery.Convert.jsonReductionDate(val);
}
if (val == "null" || val == null)
val = "";
if (val == "" && thisData.attr("watertitle") == thisData.val()) {
} else {
thisData.val(val + "");
thisData.removeClass("watertitle")
}
}
} } } }); /*********************************通用属性扩展*****************************/
jQuery.ejqInit = function () {
String.prototype.ejq_format = function (args) {
var _dic = typeof args === "object" ? args : arguments;
var reval = this.replace(/\{([^{}]+)\}/g, function (str, key) {
return _dic[key];
});
return reval;
}
String.prototype.ejq_append = function (args) {
return this + args;
}
String.prototype.ejq_appendFormat = function (appendValue, appendArgs) {
return this + appendValue.ejq_format(appendArgs);
}
String.prototype.ejq_selector = function (args) {
return $(this);
}
String.prototype.ejq_toFixed = Number.prototype.ejq_toFixed = function (d) {
var s = this + ""; if (!d) d = 0;
if (s.indexOf(".") == -1) s += "."; s += new Array(d + 1).join("0");
if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
if (a == d + 2) {
a = s.match(/\d/g); if (parseInt(a[a.length - 1]) > 4) {
for (var i = a.length - 2; i >= 0; i--) {
a[i] = parseInt(a[i]) + 1;
if (a[i] == 10) { a[i] = 0; b = i != 1; } else break;
}
}
s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");
} if (b) s = s.substr(1); return (pm + s).replace(/\.$/, "");
} return this + "";
}; }
jQuery.ejqInit(); })(window, jQuery)

ejq.js

给个赞哈

技术群 225982985 群里有大量优质IT男,欢迎大量妹子加入

功能齐全并且比较时髦的Jquery通用开源框架之【ejq.js】的更多相关文章

  1. [转]Jquery通用开源框架之【ejq.js】

    ejq是一款非常小巧的JS工具库,未压缩才50K,在jquery的基础上对jquery缺失部分作了很好的弥补作用. 优点: 1.具有内置的模板解析引擎语法和angularjs相近减少学习成本 2.能够 ...

  2. query通用开源框架

    Jquery通用开源框架之[ejq.js] 简介 ejq是一款非常小巧的JS工具库,未压缩才50K,在jquery的基础上对jquery缺失部分作了很好的弥补作用. 优点: 1.具有内置的模板解析引擎 ...

  3. 【开源推荐】AllJoyn:打造全球物联网的通用开源框架

    摘要:随着智能设备的发展,物联网逐渐进入了人们的生活.据预测,未来几乎一切东西(超过500亿台设备)都可以互联.高通公司发布了开源项目AllJoyn,这是一个能够使连接设备间进行互操作的通用软件框架和 ...

  4. LightGallery.js – 功能齐全的 Javascript Lightbox

    Lightgallery是一个轻量级的模块化.响应式的灯箱画廊,它允许您创建美丽的图像和视频画廊.借助缩略图插件的帮助,Lightgallery 允许您创建缩略图画廊.它支持触摸屏设备上滑动导航以及桌 ...

  5. Web Uploader - 功能齐全,完美兼容 IE 的上传组件

    文件上传是网站和 Web 应用程序的常用功能,一直没有一款完美的文件上传组件,因此让很多开发人员碰到头疼的浏览器兼容问题. WebUploader 是由 Baidu FEX 团队开发的一款以 HTML ...

  6. Framework7 – 赞!功能齐全的 iOS7 App 前端框架

    Framework7 是一个功能很全的 HTML 框架,用来构建 iOS7 应用程序. Framework7 允许您灵活搭建列表视图(表视图) .你可以让他们作为导航菜单,你可以在列表里面使用图标,输 ...

  7. 一个功能齐全的IOS音乐播放器应用源码

    该源码是在ios教程网拿过来的,一个不错的IOS音乐播放器应用源码,这个是我当时进公司时 我用了一晚上写的  图片都是在别的地方扒的,主要是歌词同步,及上一曲,下一曲,功能齐全了 ,大家可以学习一下吧 ...

  8. 2017最新修复福运来完整运营中时时彩源码PC+手机版本功能齐全

    QQ:1395239152 2017-3.14最新修复福运来完整运营版时时彩源码PC+手机版本功能齐全 使用php+mysql开发,并带有完整数据库.截图!!!  注意哈  带手机版  以下截图均为测 ...

  9. jQuery通用的全局遍历方法$.each()用法实例

    1.jQuery通用的全局遍历方法$.each()用法 2. test.json文件代码: 3. html代码 4.jQuery代码 <script src="jquery-1.3.1 ...

随机推荐

  1. Replication的犄角旮旯(六)-- 一个DDL引发的血案(上)(如何近似估算DDL操作进度)

    <Replication的犄角旮旯>系列导读 Replication的犄角旮旯(一)--变更订阅端表名的应用场景 Replication的犄角旮旯(二)--寻找订阅端丢失的记录 Repli ...

  2. 使用JS或jQuery模拟鼠标点击a标签事件

    <a id="alink" href="abc.aspx"  style="visibility: hidden;">下一步&l ...

  3. ENode 1.0 - 消息队列的设计思路

    开源地址:https://github.com/tangxuehua/enode 上一篇文章,简单介绍了enode框架内部的整体实现思路,用到了staged event-driven architec ...

  4. 手机淘宝UWP

    各位园主好! bug 走势: 哪天bug 足够少,哪天就可以发布了  :) 2015/10/23: 49 2015/10/26: 40 2015/10/27: 36 2015/10/28: 30 20 ...

  5. DDD领域驱动设计之领域基础设施层

    1.DDD领域驱动设计实践篇之如何提取模型 2.DDD领域驱动设计之聚合.实体.值对象 其实这里说的基础设施层只是领域层的一些接口和基类而已,没有其他的如日子工具等代码,仅仅是为了说明领域层的一些基础 ...

  6. iOS——Core Animation 知识摘抄(二)

    阴影 主要是shadowOpacity .shadowColor.shadowOffset和shadowRadius四个属性 shadowPath属性 我们已经知道图层阴影并不总是方的,而是从图层内容 ...

  7. linux expect详解(ssh自动登录)

    shell脚本实现ssh自动登录远程服务器示例: #!/usr/bin/expect spawn ssh root@192.168.22.194 expect "*password:&quo ...

  8. Azure China (4) 管理Azure China Storage Account

    <Windows Azure Platform 系列文章目录> Update 2015-05-10 强烈建议使用AzCopy工具,AzCopy命令行工具,是经过优化的.高性能Azure S ...

  9. 30分钟带你快速入门MySQL教程

    这是一篇真正适合初学者的MySQL数据库入门文章,哪怕你从来没有接触过数据库,或者说你从来没有听说过有数据库这东西,请一定要相信我,我当时就是这么过来的. 如果你刚开始接触MySQL数据库,或者你需要 ...

  10. Atitit 图像处理30大经典算法attilax总结

    Atitit 图像处理30大经典算法attilax总结 1. 识别模糊图片算法2 2. 相似度识别算法(ahash,phash,dhash)2 3. 分辨率太小图片2 4. 横条薯条广告2 5. 图像 ...