js类封装
将js方法封装成类,好处就是团队开发中避免命名冲突,部分类整理代码如下:
- function LocalStorageHelper() {
- //检测浏览器是否支持localStorage
- this.checkIsSupportLS = function () {
- return !window.localStorage || true;
- }
- //根据key获得单个localStorage的值
- this.getSingleLS = function (key) {
- if (!this.checkIsSupportLS()) { return; }
- return window.localStorage.getItem(key);
- }
- //获取localStorage所有的键值对(返回json对象)
- this.getAllLS = function () {
- if (!this.checkIsSupportLS()) { return; }
- var storage = window.localStorage,
- list = [];
- for (var i = 0; i < storage.length; i++) {
- list[i] = { 'key': storage.key(i), 'value': this.getSingleLS(storage.key(i)) };
- }
- return list;
- }
- //创建单个localStorage键值对
- this.createSingleLS = function (key, value) {
- if (!this.checkIsSupportLS()) { return; }
- var storage = window.localStorage;
- if (storage.getItem(key)) { this.removeSingleLS(key); }
- storage.setItem(key, value);
- }
- //创建多个localStorage键值对(json对象,格式:[{'key':'','value':''},{'key':'','value':''}])
- this.createListLS = function (list) {
- if (!this.checkIsSupportLS() || !list) { return; }
- var storage = window.localStorage;
- for (var i = 0; i < list.length; i++) {
- this.createSingleLS(list[i].key, list[i].value);
- }
- }
- //移除单个localStorage键值对
- this.removeSingleLS = function (key) {
- if (!this.checkIsSupportLS()) { return; }
- window.localStorage.removeItem(key);
- }
- //移除所有localStorage键值对
- this.removeAllLS = function () {
- if (!this.checkIsSupportLS()) { return; }
- window.localStorage.clear();
- }
- }
- function CommMethods() {
- //类似于C#的string.Format()
- this.format = function (str, args) {
- var result = str;
- if (args.length)
- for (var i = 0; i < args.length; i++) {
- if (typeof (args[i]) != undefined) {
- var reg = new RegExp('({[' + i + ']})', 'g');
- result = result.replace(reg, args[i]);
- }
- }
- return result;
- }
- //console.log('aaa','type:[log,info,warn,error]':default:log)
- this.log = function (msg, type) {
- //var _log = console.log;
- //console.log = function () {//模糊化输出内容
- // _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');
- //};
- var now = new Date(),
- y = now.getFullYear(),
- m = now.getMonth() + 1,//!js中月份是从0开始的
- d = now.getDate(),
- h = now.getHours(),
- min = now.getMinutes(),
- s = now.getSeconds(),
- time = this.format('{0}/{1}/{2} {3}:{4}:{5}', [y, m, d, h, min, s]),
- outMsg = this.format('{0}> {1}', [time, msg ? msg : '']);
- switch (type) {
- case 'log':
- console.log(outMsg);
- break;
- case 'info':
- console.info(outMsg)
- break;
- case 'warn':
- console.warn(outMsg);
- break;
- case 'error':
- console.error(outMsg);
- break;
- default:
- console.log(outMsg);
- break;
- }
- }
- //检测是否为正数
- this.isPositiveNumber = function (a) {
- var reg = /^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
- return reg.test(a);
- }
- //检测是否为数字--(数字包含小数)--
- this.isNumber = function (a) {
- return !isNaN(a);
- }
- //检测是否为整数
- this.isInt = function (a) {
- var reg = /^(-|\+)?\d+$/;
- return reg.test(a);;
- }
- //检测是否为有效的长日期格式 - "YYYY-MM-DD HH:MM:SS" || "YYYY/MM/DD HH:MM:SS"
- this.isDateTime = function (str) {
- var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
- if (result == null) return false;
- var d = new Date(result[1], result[3] - 1, result[4], result[5], result[6], result[7]);
- return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4] && d.getHours() == result[5] && d.getMinutes() == result[6] && d.getSeconds() == result[7]);
- }
- //检测是否为 YYYY-MM-DD || YYYY/MM/DD 的日期格式
- this.isDate = function (str) {
- var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
- if (result == null) return false;
- var d = new Date(result[1], result[3] - 1, result[4]);
- return (d.getFullYear() == result[1] && d.getMonth() + 1 == result[3] && d.getDate() == result[4]);
- }
- //检测是否为有效的电子邮件
- this.isEmail = function (str) {
- var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
- return reg.test(str);
- }
- //去除字符串的首尾的空格
- this.trim = function (str) {
- return str.replace(/(^\s*)|(\s*$)/g, "");
- }
- //返回字符串的实际长度, 一个汉字算2个长度
- this.strRealLength = function (str) {
- return str.replace(/[^\x00-\xff]/g, "**").length;
- }
- //检测是否为中国邮政编码(6位)
- this.isPostCode = function (str) {
- var reg = /[1-9]\d{5}(?!\d)/;
- return reg.test(str);
- }
- //检测是否为国内座机电话号码(0511-4405222 或 021-87888822)
- this.isTellPhone = function (str) {
- var reg = /\d{3}-\d{8}|\d{4}-\d{7}/;
- return reg.test(str);
- }
- //检测是否为腾讯QQ号
- this.isQQ = function (str) {
- var reg = /\d{15}|\d{18}/;
- return reg.test(str);
- }
- //检测是否为身份证(15位或18位)
- this.isIDCard = function (str) {
- var len = this.strRealLength(str),
- reg15 = /\d{15}|\d{18}/,
- reg18 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
- if (len === 15) {
- return reg15.test(str);
- }
- else if (len === 18) {
- return reg18.test(str);
- }
- else { return false; }
- }
- //检测文本是否为空
- this.checkIsNull = function (a) {
- return (a == '' || a == null || typeof (a) == undefined);
- }
- //XML转成JSON
- this.xmlToJson = function (xml) {
- // Create the return object
- var obj = {};
- if (xml.nodeType == 1) { // element
- // do attributes
- if (xml.attributes.length > 0) {
- obj["@attributes"] = {};
- for (var j = 0; j < xml.attributes.length; j++) {
- var attribute = xml.attributes.item(j);
- obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
- }
- }
- } else if (xml.nodeType == 3) { // text
- obj = xml.nodeValue;
- }
- // do children
- if (xml.hasChildNodes()) {
- for (var i = 0; i < xml.childNodes.length; i++) {
- var item = xml.childNodes.item(i);
- var nodeName = item.nodeName;
- if (typeof (obj[nodeName]) == "undefined") {
- obj[nodeName] = xmlToJson(item);
- } else {
- if (typeof (obj[nodeName].length) == "undefined") {
- var old = obj[nodeName];
- obj[nodeName] = [];
- obj[nodeName].push(old);
- }
- obj[nodeName].push(xmlToJson(item));
- }
- }
- }
- return obj;
- }
- //去除数组重复项
- this.removeListRepeat = function (list) {
- var $ = list,
- o1 = {},
- o2 = {},
- o3 = [],
- o;
- for (var i = 0; o = $[i]; i++) {
- if (o in o1) {
- if (!(o in o2)) o2[o] = o;
- delete $[i];
- } else {
- o1[o] = o;
- }
- }
- $.length = 0;
- for (o in o1) {
- $.push(o);
- }
- for (o in o2) {
- o3.push(o);
- }
- return o3;
- }
- }
- function CookieHelper() {
- // 1. 设置COOKIE
- // 简单型
- this.setCookieSimple = function (c_name, value, expiredays) {
- var exdate = new Date();
- exdate.setDate(exdate.getDate() + expiredays);
- document.cookie = c_name + "=" + escape(value) +
- ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
- }
- // 完整型
- this.setCookieBoth = function (name, value, expires, path, domain, secure) {
- var expDays = expires * 24 * 60 * 60 * 1000,
- expDate = new Date();
- expDate.setTime(expDate.getTime() + expDays);
- var expString = ((expires == null) ? '' : (';expires=' + expDate.toGMTString())),
- pathString = ((path == null) ? '' : (";path=" + path)),
- domainString = ((domain == null) ? '' : (';domain=' + domain)),
- secureString = ((secure == true) ? ';secure' : '');
- document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString;
- }
- // 2.获取指定名称的cookie值:
- this.getCookie = function (c_name) {
- if (document.cookie.length > 0) {
- c_start = document.cookie.indexOf(c_name + '=')
- if (c_start != -1) {
- c_start = c_start + c_name.length + 1
- c_end = document.cookie.indexOf(';', c_start)
- if (c_end == -1) c_end = document.cookie.length
- return unescape(document.cookie.substring(c_start, c_end))
- }
- }
- return ''
- }
- // 3.删除指定名称的cookie:
- this.removeCookie = function (name) {
- var expDate = new Date();
- expDate.setTime(expDate.getTime() - 100);
- document.cookie = name + '=;expires=' + expDate.toGMTString();
- }
- // 4. 检测cookie:
- this.checkIsSupportCookie = function () {
- var result = false;
- if (navigator.cookiesEnabled) {return true; }
- document.cookie = 'testcookie=yes;';
- var setCookie = document.cookie;
- if (setCookie.indexOf('testcookie=yes') > -1) {
- result = true;
- } else {
- document.cookie = '';
- }
- return result;
- }
- }
- $(function () {
- var localstoragehelper = new LocalStorageHelper();
- var commmethod = new CommMethods();
- localstoragehelper.checkIsSupportLS();
- commmethod.checkIsNull();
- });
js类封装的更多相关文章
- JS类的封装及实现代码
js并不是一种面向对向的语言, 没有提供对类的支持, 因此我们不能像在传统的语言里那样 用class来定义类, 但我们可以利用js的闭包封装机制来实现js类, 我们来封装一个简的Shape类. 1. ...
- js创建类(封装)
js如何创建类(封装) 学过其他面向对象语言的JavaScripter,可能都应用过类,如:class{},等定义的一系列方法, 但是初学者看是学习js的时候,经常会看到这样一句话,那就是Ja ...
- JS 对象封装的常用方式
JS是一门面向对象语言,其对象是用prototype属性来模拟的,下面,来看看如何封装JS对象. 常规封装 function Person (name,age,sex){ this.name = na ...
- 自己手写的自动完成js类
在web开发中,为了提高用户体验,会经常用到输入框的自动完成功能,不仅帮助用户进行快速输入,最重要的是帮助那些“记不全要输入什么”的用户进行选择.这个功能有很多插件已经实现了,为了适应项目的特殊需求, ...
- js类(继承)(二)
1. 定义js类 js并不是一种面向对向的语言, 没有提供对类的支持, 因此我们不能像在传统的语言里那样 用class来定义类, 但我们可以利用js的闭包封装机制来实现js类, 我们来封装一个简的Sh ...
- JS类继承常用方式发展史
JS类继承常用方式发展史 涉及知识点 构造函数方式继承 1-继承单个对象 1.1 多步走初始版 1.2 多步走优化版 1.3 Object.create()方式 2-继承多个对象 2.1 遍历 Obj ...
- .Net Core ORM选择之路,哪个才适合你 通用查询类封装之Mongodb篇 Snowflake(雪花算法)的JavaScript实现 【开发记录】如何在B/S项目中使用中国天气的实时天气功能 【开发记录】微信小游戏开发入门——俄罗斯方块
.Net Core ORM选择之路,哪个才适合你 因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别 ...
- ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪
ASP.NET MVC深入浅出(被替换) 一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...
- 使用jq把js代码封装一个自己的插件
为什么要把js功能封装成插件呢?我觉得有以下几点吧 1.最基本的原因就是便于代码复用. 2.便于维护和管理. 3.提升自身的能力. 4.避免各个相同功能组件的干扰,以及一些作用域会相互影响的问题. j ...
随机推荐
- 二十分钟弄懂C++11 的 rvalue reference (C++ 性能剖析 (5))
C++ 11加了许多新的功能.其中对C++性能和我们设计class的constructor或assignment可能产生重大影响的非rvalue reference莫属!我看了不少资料,能说清它的不多 ...
- php小知识点
1.字符串可以里面的字符可以像数组一样访问,比如$s = "123";$s[1]就等于2,如果字符串为中文则会乱码,需要使用mb_substr进行截取: 2.php中的单引号(' ...
- Linux下的Job Control(转:http://blog.chinaunix.net/uid-26495963-id-3062757.html)
一.Job的概念 Job是指在批处理的环境中,为完成某一任务而进行一系列操作的总称.在个人接触计算机的年代,批处理的环境已经不容见到了,只有一些特殊的行业和环境下还在使用这样的概念,仅在书本中接触过. ...
- QComboBox实现复选功能
需求: 下拉列表有复选功能 不可编辑 显示所有选中项 关于QComboBox的复选功能有几种方案: QStandardItemModel + QStandardItem QListWidget + ...
- MySql存储过程—2、第一个MySql存储过程的建立
看看如何创建一个存储过程.虽然通过命令行可以创建,但基本通过MySQL提供的Query browser来创建. 1.首先我们通过Administrator在test数据库中创建一个简单的表名叫”pro ...
- iOS开发网络篇-JSON文件的解析
一.什么是JSON数据 1.JSON的简单介绍 JSON:是一种轻量级的传输数据的格式,用于数据的交互 JSON是javascript语言的一个子集.javascript是个脚本语言(不需要编译),用 ...
- FileUpload 改变控件显示的文字
浏览
- C语言字符数组越界现象
今天在用C的过程中发现一个奇怪的现象.代码如下: ]; chs[] = 'a'; chs[] = 'b'; printf(]); 结果 输出 是 a. 在网上查了一下.有个网友是这样回答的: “ 我 ...
- Hadoop 学习笔记(一) HDFS API
http://www.cnblogs.com/liuling/p/2013-6-17-01.html 这个也不错http://www.teamwiki.cn/hadoop/thrift thrift编 ...
- 【转】带checkbox的ListView实现(二)——自定义Checkable控件的实现方法
原文网址:http://blog.csdn.net/harvic880925/article/details/40475367 前言:前一篇文章给大家展示了传统的Listview的写法,但有的时候我们 ...