博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
发布一个JavaScript工具类库jutil,欢迎使用,欢迎补充,欢迎挑错!
阅读量:5220 次
发布时间:2019-06-14

本文共 9462 字,大约阅读时间需要 31 分钟。

由来

  工作中jQuery用的比较多,但jQuery再强大也有些方法是没有的,以前的做法就是东拼西凑,今天终于下定决心把平时用到的一些方法加以整理,这就是jutil的由来。

  当前只有17个方法,涉及到的有Array、HTML、Cookie & localStorage、Date、String。这些方法都采用了原生的JS,不依赖于jQuery。

  都说好的设计是易于理解的,不用过多介绍,而这也是我现在想达到的目标,因此下面的介绍会比较简单,如果大家哪个地方看不明白或有更好的建议,请提出来,我再优化。

Array相关  

  • jutil.arrayDistinct(Array)
  • jutil.arrayIndexOf(Array,Item)

  实现代码如下:

View Code
arrayDistinct: function (arr) {    var tempArr = {};    for (var i = 0; i < arr.length; i++) {        if (tempArr[arr[i] + 1]) {            arr.splice(i, 1);            i--;            continue;        }        tempArr[arr[i] + 1] = true;    }    tempArr = null;    return arr;},arrayIndexOf: function (arr, obj, iStart) {    if (Array.prototype.indexOf) {        return arr.indexOf(obj, (iStart || 0));    }    else {        for (var i = (iStart || 0), j = arr.length; i < j; i++) {            if (arr[i] === obj) {                return i;            }        }        return -1;    }},

  第一个方法参考了菜鸟程序员的博文:

HTML相关  

  • jutil.htmlEncode(sHtml)
  • jutil.htmlDecode(sHtml)

  实现代码如下:

View Code
htmlEncode: function (sHtml) {    var div = this.document.createElement("div"),        text = this.document.createTextNode(sHtml);    div.appendChild(text);    return div.innerHTML;},htmlDecode: function (sHtml) {    var div = this.document.createElement("div");    div.innerHTML = sHtml;    return div.innerText || div.textContent;},

  如果有用jQuery,上面代码可以进一步简化为:

View Code
htmlEncode: function (sHtml) {    return $("div").text(sHtml).html();},htmlDecode: function (sHtml) {    return $("div").html(sHtml).text();},

Cookie & localStorage相关

  • jutil.getCookie(sKey)
  • jutil.setCookie(sKey, sValue, iExpireSeconds)
  • jutil.deleteCookie(sKey)
  • jutil.getStorage(sKey)//如果浏览器支持HTML5本地存储(localStorage)优先用本地存储,否则用cookie,下同
  • jutil.setStorage(sKey, sValue, iExpireSeconds)
  • jutil.deleteStorage(sKey)

  实现代码如下:

View Code
getCookie: function (sKey) {    if (!sKey)        return "";    if (document.cookie.length > 0) {        var startIndex = document.cookie.indexOf(sKey + "=")        if (startIndex != -1) {            startIndex = startIndex + sKey.length + 1            var endIndex = document.cookie.indexOf(";", startIndex)            if (endIndex == -1) {                endIndex = document.cookie.length;            }            return decodeURIComponent(document.cookie.substring(startIndex, endIndex));        }    }    return ""},setCookie: function (sKey, sValue, iExpireSeconds) {    if (!sKey)        return;    var expireDate = new Date();    expireDate.setTime(expireDate.getTime() + iExpireSeconds * 1000);    this.document.cookie = sKey + "=" + encodeURIComponent(sValue) +     ";expires=" + expireDate.toGMTString() + ";";},deleteCookie: function (sKey) {    if (!sKey)        return;    this.document.cookie = sKey + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';},getStorage: function (sKey) {    if (!sKey)        return;    if (window.localStorage) {        return decodeURIComponent(localStorage.getItem(sKey));    }    else {        return this.getCookie(sKey);    }},setStorage: function (sKey, sValue, iExpireSeconds) {    if (!sKey)        return;    if (window.localStorage) {        localStorage.setItem(sKey, encodeURIComponent(sValue));    }    else {        this.setCookie(sKey, sValue, iExpireSeconds);    }},deleteStorage: function (sKey) {    if (!sKey)        return;    if (window.localStorage) {        localStorage.removeItem(sKey);    }    else {        this.deleteCookie(sKey);    }},

Date相关  

  • jutil.daysInFebruary(obj)//obj:数字(如2012)或时间(如new Date())
  • jutil.daysInYear(obj)//obj:数字(如2012)或时间(如new Date())
  • jutil.dateFormat(date, sFormat, sLanguage)//sFormat:yyyy为年,MM为月,DD为日,hh为时,mm为分,ss为秒,MMM为月份,EEE为星期。sLanguage:默认为中文,可以设置成英文(en)
  • jutil.dateDiff(biggerDate, smallerDate)
  • jutil.dateInterval(biggerDate, smallerDate)

  从名子大家可能看不出最后两个方法的区别,这里命名可能是有些问题,大家有没有推荐的?

  dateDiff表示两个时间之间相隔多长时间,返回的是"10分钟"、"2天"等字符串,一般用在要显示"XX分钟前"、"XX天前"时。

  dateInterval表示两个时间精确差(精确到秒),返回的是"1天:1小时:1分钟:1秒"这样的字符串。

  实现代码如下:

View Code
daysInFebruary: function (obj) {    var year = 0;    if (obj instanceof Date) {        year = obj.getFullYear();    }    else if (typeof obj === "number") {        year = obj;    }    else {        return 0;    }    if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {        return 29;    }    return 28;},daysInYear: function (obj) {    var year = 0;    if (obj instanceof Date) {        year = obj.getFullYear();    }    else if (typeof obj === "number") {        year = obj;    }    else {        return 0;    }    if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {        return 366;    }    return 365;},dateFormat: function (date, sFormat, sLanguage) {    var time = {};    time.Year = date.getFullYear();    time.TYear = ("" + time.Year).substr(2);    time.Month = date.getMonth() + 1;    time.TMonth = time.Month < 10 ? "0" + time.Month : time.Month;    time.Day = date.getDate();    time.TDay = time.Day < 10 ? "0" + time.Day : time.Day;    time.Hour = date.getHours();    time.THour = time.Hour < 10 ? "0" + time.Hour : time.Hour;    time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;    time.Thour = time.hour < 10 ? "0" + time.hour : time.hour;    time.Minute = date.getMinutes();    time.TMinute = time.Minute < 10 ? "0" + time.Minute : time.Minute;    time.Second = date.getSeconds();    time.TSecond = time.Second < 10 ? "0" + time.Second : time.Second;    time.Millisecond = date.getMilliseconds();    time.Week = date.getDay();    var MMMArrEn = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],        MMMArr = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],        WeekArrEn = ["Sun", "Mon", "Tue", "Web", "Thu", "Fri", "Sat"],        WeekArr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],        oNumber = time.Millisecond / 1000;    if (sFormat != undefined && sFormat.replace(/\s/g, "").length > 0) {        if (sLanguage != undefined && sLanguage === "en") {            MMMArr = MMMArrEn.slice(0);            WeekArr = WeekArrEn.slice(0);        }        sFormat = sFormat.replace(/yyyy/ig, time.Year)        .replace(/yyy/ig, time.Year)        .replace(/yy/ig, time.TYear)        .replace(/y/ig, time.TYear)        .replace(/MMM/g, MMMArr[time.Month - 1])        .replace(/MM/g, time.TMonth)        .replace(/M/g, time.Month)        .replace(/dd/ig, time.TDay)        .replace(/d/ig, time.Day)        .replace(/HH/g, time.THour)        .replace(/H/g, time.Hour)        .replace(/hh/g, time.Thour)        .replace(/h/g, time.hour)        .replace(/mm/g, time.TMinute)        .replace(/m/g, time.Minute)        .replace(/ss/ig, time.TSecond)        .replace(/s/ig, time.Second)        .replace(/fff/ig, time.Millisecond)        .replace(/ff/ig, oNumber.toFixed(2) * 100)        .replace(/f/ig, oNumber.toFixed(1) * 10)        .replace(/EEE/g, WeekArr[time.Week]);    }    else {        sFormat = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + ":" + time.Minute + ":" + time.Second;    }    return sFormat;},dateDiff: function (biggerDate, smallerDate) {    var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000);    if (intervalSeconds < 60) {        return intervalSeconds + "秒";    }    else if (intervalSeconds < 60 * 60) {        return Math.floor(intervalSeconds / 60) + "分钟";    }    else if (intervalSeconds < 60 * 60 * 24) {        return Math.floor(intervalSeconds / (60 * 60)) + "小时";    }    else if (intervalSeconds < 60 * 60 * 24 * 7) {        return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";    }    else if (intervalSeconds < 60 * 60 * 24 * 31) {        return Math.floor(intervalSeconds / (60 * 60 * 24 * 7)) + "周";    }    else if (intervalSeconds < 60 * 60 * 24 * 365) {        return Math.floor(intervalSeconds / (60 * 60 * 24 * 30)) + "月";    }    else if (intervalSeconds < 60 * 60 * 24 * 365 * 1000) {        return Math.floor(intervalSeconds / (60 * 60 * 24 * 365)) + "年";    }    else {        return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";    }},dateInterval: function (biggerDate, smallerDate) {    var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000),        day = Math.floor(intervalSeconds / (60 * 60 * 24)),        hour = Math.floor((intervalSeconds - day * 24 * 60 * 60) / 3600),        minute = Math.floor((intervalSeconds - day * 24 * 60 * 60 - hour * 3600) / 60),        second = Math.floor(intervalSeconds - day * 24 * 60 * 60 - hour * 3600 - minute * 60);    return day + "天:" + hour + "小时:" + minute + "分钟:" + second + "秒";},

  这里的dateFormat的实现代码参考的是我之前的一篇博客:

String相关

  • jutil.replaceURLWithHTMLLinks(sText, bBlank)
  • jutil.getLength(sVal, bChineseDouble)

  这个就比较简单了,直接上代码:

View Code
replaceURLWithHTMLLinks: function (sText, bBlank) {    var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;    if (bBlank) {        sText = sText.replace(pattern, "$1");    }    else {        sText = sText.replace(pattern, "$1");    }    return sText;},getLength: function (sVal, bChineseDouble) {    var chineseRegex = /[\u4e00-\u9fa5]/g;    if (bChineseDouble != undefined && bChineseDouble === false) {        return sVal.length;    }    else {        if (chineseRegex.test(sVal)) {            return sVal.replace(chineseRegex, "zz").length;        }        return sVal.length;    }}

测试代码

  测试效果:

小结

  后面会继续添加正则方面的内容,本文也会持续更新。目前JS下载链接:

  欢迎使用,欢迎补充,欢迎挑错!

  本文首发博客园:

重构信息

  针对评论中出现的问题,我作了一次重构,请参考:

转载于:https://www.cnblogs.com/artwl/archive/2012/07/09/2583114.html

你可能感兴趣的文章
[coreData]Transformable 格式的attribute ,及自定义格式的attribute
查看>>
MyBatis学习总结——MyBatis快速入门
查看>>
APP主流盈利模式
查看>>
python 连接数据库操作
查看>>
(爱加密系列教程八)Android APP如何防止二次打包
查看>>
poj 3279 Fliptile (简单搜索)
查看>>
手机触屏版页面开发总结
查看>>
尼克的任务
查看>>
VueJs2.0建议学习路线
查看>>
Request库使用response.text返回乱码问题
查看>>
window.location.href()采用post传递数据
查看>>
java学习多线程之线程状态
查看>>
关情纸尾-----OC-面向对象->类和对象
查看>>
汇编语言程序设计第六章
查看>>
python enumerate
查看>>
Pointer Lock
查看>>
加不加入创业公司,看了本文再决定
查看>>
【POJ】1084 Square Destroyer
查看>>
创建父子控制器
查看>>
Cent OS 7.4 源码搭建LAMP
查看>>