封装cookie.js、EventUtil.js、

最近学习了javascript,封装好的东西看起来舒服,以备需要的时候拉出来,jquery对javascript做了很好的封装!以后会多用jquery多些

var
CookieUtil = {get: function (name){var cookieName = encodeURIComponent(name) + "=",cookieStart = document.cookie.indexOf(cookieName),cookieValue = null,cookieEnd;if (cookieStart > -1){cookieEnd = document.cookie.indexOf(";", cookieStart);if (cookieEnd == -1){cookieEnd = document.cookie.length;}cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));} return cookieValue;},set: function (name, value, expires, path, domain, secure) {var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);if (expires instanceof Date) {cookieText += "; expires=" + expires.toGMTString();}if (path) {cookieText += "; path=" + path;}if (domain) {cookieText += "; domain=" + domain;}if (secure) {cookieText += "; secure";}document.cookie = cookieText;},unset: function (name, path, domain, secure){this.set(name, "", new Date(0), path, domain, secure);}};

/*SubCookieUtil.js*/
var SubCookieUtil = {

    get: function (name, subName){
        var subCookies = this.getAll(name);
        if (subCookies){
            return subCookies[subName];
        } else {
            return null;
        }
    },
    
    getAll: function(name){
        var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null,
            cookieEnd,
            subCookies,
            i,
            parts,
            result = {};
            
        if (cookieStart > -1){
            cookieEnd = document.cookie.indexOf(";", cookieStart)
            if (cookieEnd == -1){
                cookieEnd = document.cookie.length;
            }
            cookieValue = document.cookie.substring(cookieStart + cookieName.length, cookieEnd);
            
            if (cookieValue.length > 0){
                subCookies = cookieValue.split("&");
                
                for (i=0, len=subCookies.length; i < len; i++){
                    parts = subCookies[i].split("=");
                    result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
                }
    
                return result;
            }  
        }

        return null;
    },
    
    set: function (name, subName, value, expires, path, domain, secure) {
    
        var subcookies = this.getAll(name) || {};
        subcookies[subName] = value;
        this.setAll(name, subcookies, expires, path, domain, secure);

    },
    
    setAll: function(name, subcookies, expires, path, domain, secure){
    
        var cookieText = encodeURIComponent(name) + "=",
            subcookieParts = new Array(),
            subName;
        
        for (subName in subcookies){
            if (subName.length > 0 && subcookies.hasOwnProperty(subName)){
                subcookieParts.push(encodeURIComponent(subName) + "=" + encodeURIComponent(subcookies[subName]));
            }
        }
        
        if (subcookieParts.length > 0){
            cookieText += subcookieParts.join("&");
                
            if (expires instanceof Date) {
                cookieText += "; expires=" + expires.toGMTString();
            }
        
            if (path) {
                cookieText += "; path=" + path;
            }
        
            if (domain) {
                cookieText += "; domain=" + domain;
            }
        
            if (secure) {
                cookieText += "; secure";
            }
        } else {
            cookieText += "; expires=" + (new Date(0)).toGMTString();
        }
    
        document.cookie = cookieText;        
    
    },
    
    unset: function (name, subName, path, domain, secure){
        var subcookies = this.getAll(name);
        if (subcookies){
            delete subcookies[subName];
            this.setAll(name, subcookies, null, path, domain, secure);
        }
    },
    
    unsetAll: function(name, path, domain, secure){
        this.setAll(name, null, new Date(0), path, domain, secure);
    }

};
var EventUtil = {addHandler: function(element, type, handler){if (element.addEventListener){element.addEventListener(type, handler, false);} else if (element.attachEvent){element.attachEvent("on" + type, handler);} else {element["on" + type] = handler;}},getButton: function(event){if (document.implementation.hasFeature("MouseEvents", "2.0")){return event.button;} else {switch(event.button){case 0:case 1:case 3:case 5:case 7:return 0;case 2:case 6:return 2;case 4: return 1;}}},getCharCode: function(event){if (typeof event.charCode == "number"){return event.charCode;} else {return event.keyCode;}},getClipboardText: function(event){var clipboardData =  (event.clipboardData || window.clipboardData);return clipboardData.getData("text");},getEvent: function(event){return event ? event : window.event;},getRelatedTarget: function(event){if (event.relatedTarget){return event.relatedTarget;} else if (event.toElement){return event.toElement;} else if (event.fromElement){return event.fromElement;} else {return null;}},getTarget: function(event){return event.target || event.srcElement;},getWheelDelta: function(event){if (event.wheelDelta){return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta : event.wheelDelta);} else {return -event.detail * 40;}},preventDefault: function(event){if (event.preventDefault){event.preventDefault();} else {event.returnValue = false;}},removeHandler: function(element, type, handler){if (element.removeEventListener){element.removeEventListener(type, handler, false);} else if (element.detachEvent){element.detachEvent("on" + type, handler);} else {element["on" + type] = null;}},setClipboardText: function(event, value){if (event.clipboardData){event.clipboardData.setData("text/plain", value);} else if (window.clipboardData){window.clipboardData.setData("text", value);}},stopPropagation: function(event){if (event.stopPropagation){event.stopPropagation();} else {event.cancelBubble = true;}}};
var client = function(){//rendering enginesvar engine = {            ie: 0,gecko: 0,webkit: 0,khtml: 0,opera: 0,//complete versionver: null  };//browsersvar browser = {//browsersie: 0,firefox: 0,safari: 0,konq: 0,opera: 0,chrome: 0,//specific versionver: null};//platform/device/OSvar system = {win: false,mac: false,x11: false,//mobile devicesiphone: false,ipod: false,ipad: false,ios: false,android: false,nokiaN: false,winMobile: false,//game systemswii: false,ps: false };    //detect rendering engines/browsersvar ua = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6";//navigator.userAgent;    if (window.opera){engine.ver = browser.ver = window.opera.version();engine.opera = browser.opera = parseFloat(engine.ver);} else if (/AppleWebKit\/(\S+)/.test(ua)){engine.ver = RegExp["$1"];engine.webkit = parseFloat(engine.ver);//figure out if it's Chrome or Safariif (/Chrome\/(\S+)/.test(ua)){browser.ver = RegExp["$1"];browser.chrome = parseFloat(browser.ver);} else if (/Version\/(\S+)/.test(ua)){browser.ver = RegExp["$1"];browser.safari = parseFloat(browser.ver);} else {//approximate versionvar safariVersion = 1;if (engine.webkit < 100){safariVersion = 1;} else if (engine.webkit < 312){safariVersion = 1.2;} else if (engine.webkit < 412){safariVersion = 1.3;} else {safariVersion = 2;}   browser.safari = browser.ver = safariVersion;        }} else if (/KHTML\/(\S+)/.test(ua) || /Konqueror\/([^;]+)/.test(ua)){engine.ver = browser.ver = RegExp["$1"];engine.khtml = browser.konq = parseFloat(engine.ver);} else if (/rv:([^\)]+)\) Gecko\/\d{8}/.test(ua)){    engine.ver = RegExp["$1"];engine.gecko = parseFloat(engine.ver);//determine if it's Firefoxif (/Firefox\/(\S+)/.test(ua)){browser.ver = RegExp["$1"];browser.firefox = parseFloat(browser.ver);}} else if (/MSIE ([^;]+)/.test(ua)){    engine.ver = browser.ver = RegExp["$1"];engine.ie = browser.ie = parseFloat(engine.ver);}//detect browsersbrowser.ie = engine.ie;browser.opera = engine.opera;//detect platformvar p = navigator.platform;system.win = p.indexOf("Win") == 0;system.mac = p.indexOf("Mac") == 0;system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);//detect windows operating systemsif (system.win){if (/Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/.test(ua)){if (RegExp["$1"] == "NT"){switch(RegExp["$2"]){case "5.0":system.win = "2000";break;case "5.1":system.win = "XP";break;case "6.0":system.win = "Vista";break;case "6.1":system.win = "7";break;default:system.win = "NT";break;                }                            } else if (RegExp["$1"] == "9x"){system.win = "ME";} else {system.win = RegExp["$1"];}}}//mobile devicessystem.iphone = ua.indexOf("iPhone") > -1;system.ipod = ua.indexOf("iPod") > -1;system.ipad = ua.indexOf("iPad") > -1;system.nokiaN = ua.indexOf("NokiaN") > -1;//windows mobileif (system.win == "CE"){system.winMobile = system.win;} else if (system.win == "Ph"){if(/Windows Phone OS (\d+.\d+)/.test(ua)){;system.win = "Phone";system.winMobile = parseFloat(RegExp["$1"]);}}//determine iOS versionif (system.mac && ua.indexOf("Mobile") > -1){if (/CPU (?:iPhone )?OS (\d+_\d+)/.test(ua)){system.ios = parseFloat(RegExp.$1.replace("_", "."));} else {system.ios = 2;  //can't really detect - so guess
        }}//determine Android versionif (/Android (\d+\.\d+)/.test(ua)){system.android = parseFloat(RegExp.$1);}//gaming systemssystem.wii = ua.indexOf("Wii") > -1;system.ps = /playstation/i.test(ua);//return itreturn {engine:     engine,browser:    browser,system:     system        };}();
//跨浏览器添加事件 
function addEvent(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent) {
        obj.attachEvent('on' + type, function () {
            fn.call(obj);
        });
    }
}

//跨浏览器移除事件
function removeEvent(obj, type, fn) {
    if (obj.removeEventListener) {
        obj.removeEventListener(type, fn, false);
    } else if (obj.detachEvent) {
        obj.detachEvent('on' + type, fn);
    }
}

//跨浏览器阻止默认行为
function preDef(evt) {
    var e = evt || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}

//跨浏览器获取目标对象
function getTarget(evt) {
    if (evt.target) {        //W3C
        return evt.target;
    } else if (window.event.srcElement) {        //IE
        return window.event.srcElement;
    }
}

//跨浏览器获取字符编码
function getCharCode(evt) {
    var e = evt || window.event;
    if (typeof e.charCode == 'number') {
        return e.charCode;
    } else {
        return e.keyCode;
    }
}

function createXHR() {
    if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    } else if (typeof ActiveXObject != 'undefined') {
        var version = [
                                    'MSXML2.XMLHttp.6.0',
                                    'MSXML2.XMLHttp.3.0',
                                    'MSXML2.XMLHttp'
        ];
        for (var i = 0; version.length; i ++) {
            try {
                return new ActiveXObject(version[i]);
            } catch (e) {
                //跳过
            }    
        }
    } else {
        throw new Error('您的系统或浏览器不支持XHR对象!');
    }
}


//名值对转换为字符串
function params(data) {
    var arr = [];
    for (var i in data) {
        arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
    }
    return arr.join('&');
}



//
封装ajax function ajax(obj) {var xhr = createXHR();obj.url = obj.url + '?rand=' + Math.random();obj.data = params(obj.data);if (obj.method === 'get') obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data;if (obj.async === true) {xhr.onreadystatechange = function () {if (xhr.readyState == 4) {callback();}};}xhr.open(obj.method, obj.url, obj.async);if (obj.method === 'post') {xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send(obj.data); } else {xhr.send(null);}if (obj.async === false) {callback();}function callback() {if (xhr.status == 200) {obj.success(xhr.responseText); //回调传递参数} else {alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);} } }//调用ajax addEvent(document, 'click', function () {ajax({method : 'post',url : 'demo3.php',data : {'name' : 'Lee','age' : 100},success : function (text) {alert(text);},async : true}); });

 

转载于:https://www.cnblogs.com/double405/p/5089196.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/272519.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

实现linux cp 命令和修改配置文件

cp指令用来代码的拷贝 以下由文件编程代码实现 代码演示 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <unistd.h> #include <string.h>#include <stdlib.h> int main(int argc…

最实用前端开发框架对比评测

现在&#xff0c;各种开发框架层出不穷&#xff0c;但是&#xff0c;真正的精品却为数不多。今天我们根据Github上的流行程度整理了2014年最受欢迎的5个前端开发框架&#xff0c;并进行对比说明&#xff0c;希望帮助有需要的朋友选择合适自己的前端框架。1. BootstrapBootstrap…

HBase1.0.0 实现数据增删查

HBase1.0.0 即Hadoop 2.6 采用maven 的方式实现HBase数据简单操作 import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random;import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.a…

linux 写结构体到文件

将整数写入到文件 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <unistd.h> #include <string.h>#include <stdlib.h> int main() {int fd;int data100;int data20;fdopen("…

程序员常访问的国外技术交流网站

技术人员经常会在各种技术交流社区游逛&#xff0c;大家互相学习、交流、分享、帮助。互联网拉近了地球人的距离&#xff0c;让全世界的技术人员可以聚集在一起分享交流。当然因为多方面原因&#xff0c;通常最新最权威的技术知识传到国内存在一定“时差”。本文将给大家分享技…

标准C库对文件操作的引入

modeopen和fopen的区别 fopen、fread、fwrite的使用 &#xff08;1&#xff09;fopen FILE *fopen(const char *path, const char *mode);path&#xff1a;文件路径 mode&#xff1a;以什么权限打开&#xff0c;要用双引号 它的返回值并不是文件描述符 若失败返回NULL 若操作成…

转载爱哥自定义View系列--Paint详解

上图是paint中的各种set方法 这些属性大多我们都可以见名知意&#xff0c;很好理解&#xff0c;即便如此&#xff0c;哥还是带大家过一遍逐个剖析其用法&#xff0c;其中会不定穿插各种绘图类比如Canvas、Xfermode、ColorFilter等等的用法。 set(Paint src) 顾名思义为当前画笔…

只有程序员才懂这些黑色幽默!

也是机缘巧合&#xff0c;让我一个之前工作从未接触过程序员的人&#xff0c;现在成天和程序员打交道&#xff0c;要知道&#xff0c;不懂技术&#xff0c;往往他们想和你幽默的搞笑一下&#xff0c;未必能读懂。都说程序员情商低&#xff0c;不爱说话&#xff0c;比较闷骚。可…

tiny4412 linux+qtopia nfs网络文件系统的挂载

1,首先确定uboot启动内核的bootargs参数 Linux-CommandLine root/dev/nfs nfsroot192.168.1.131:/home/tiny4412/rootfs_qtopia_qt4 ip192.168.1.230:192.168.1.131:192.168.1.1:255.255.255.0::eth0:off rootfstypenfs consolettySAC0,115200 init/linuxrc ctp2 skipcaliy uh…

Linux 进程、父进程、子进程

进程和程序的区别 一、 进程是动态的&#xff0c;程序是静态的&#xff1a;程序是有序代码的集合&#xff0c;进程是程序的执行。进程有核心态/用户态。 二、 进程是暂时的&#xff0c;程序是永久的&#xff1b;进程是一个状态变化的过程&#xff0c;程序可以长久保存 三、进…

几款开源富文本编辑器优缺点比较

1、百度UEditor 优点&#xff1a;插件多&#xff0c;基本满足各种需求&#xff0c;类似贴吧中的回复界面。缺点&#xff1a;不再维护&#xff0c;文档极少&#xff0c;使用并不普遍&#xff0c;图片只能上传到本地服务器&#xff0c;如果需要上传到其他服务器需要改动源码&…

C程序的储存空间是如何分配?

可执行程序包括BSS段、数据段、代码段。 在类UNIX系统下可使用size命令查看可执行文件的段大小信息。如size a.out&#xff1a; ~/Desktop/MyC$ size a.outtext data bss dec hex filename1672 600 8 2280 8e8 a.out1.数据段存放已初始化的全…

详细讲解Android的网络通信(HttpUrlConnection和HttpClient)

前言&#xff0c;Android的网络通信的方式有两种&#xff1a;使用Socket或者HTTP&#xff0c;今天这一篇我们详细讲解使用HTTP实现的网络通信&#xff0c;HTTP又包括两种方式编程方式&#xff1a; &#xff08;1&#xff09;HttpUrlConnection&#xff1b; &#xff08;2&#…

常见通信协议HTTP、TCP、UDP的简单介绍

TCP HTTP UDP:都是通信协议&#xff0c;也就是通信时所遵守的规则&#xff0c;只有双方按照这个规则“说话”&#xff0c;对方才能理解或为之服务。TCP HTTP UDP三者的关系:TCP/IP是个协议组&#xff0c;可分为四个层次&#xff1a;网络接口层、网络层、传输层和应用层…

创建进程相关函数

fork函数 pid_t fork(void); fork函数调用成功&#xff0c; 返回两次 在fork函数执行完毕后 如果创建新进程成功&#xff0c;则出现两个进程 一个是子进程&#xff0c;一个是父进程 在子进程中&#xff0c;fork函数返回0 在父进程中&#xff0c;fork返回新创建子进程的进程ID…

实现Windows和Linux之间的文件共享

一、windows 向linux共享文件(这里都是以win10和ubuntu为例)首先&#xff0c;打开网络共享中心。如图1图1打开更改高级共享设置&#xff08;图2&#xff09;图 2选择启用网络发现以及启用文件和打印机共享&#xff0c;然后点击保存更改。接着&#xff0c;选择你要共享的文件夹&…

鸡啄米MFC教程笔记之七:对话框:为控件添加消息处理函数

MFC为对话框和控件等定义了诸多消息&#xff0c;我们对它们操作时会触发消息&#xff0c;这些消息最终由消息处理函数处理。比如我们点击按钮时就会产生BN_CLICKED消息&#xff0c;修改编辑框内容时会产生EN_CHANGE消息等。一般为了让某种操作达到效果&#xff0c;我们只需要实…

进程的退出方式以及僵尸进程和孤儿进程

&#xff08;1&#xff09;正常退出 &#xff08;2&#xff09;异常退出 检查wait和waitpid所返回的终止状态的宏 宏说明WIFEXITED(status)若为正常终止子进程返回的状态&#xff0c;则为真。对于这种情况可执行WEXITSTATUS(status)&#xff0c;取子进程传送给exit、_exit或_…

java中的动态代理----自己手动实现

代码使用了common-io&#xff0c;需要其jar 1 接口 Java代码 public interface Pruduct { void selling(); } 2 书籍类 Java代码 public class Book implements Pruduct { Override public void selling() { try { Thread.sleep(1000…

Code Project精彩系列(1)

ApplicationsCrafting a C# forms Editor From scratchhttp://www.codeproject.com/csharp/SharpFormEditorDemo.asp建立一个类似C#的环境, 实现控件拖拉&#xff0c;属性Packet Capture and Analayzer网络封包截获http://www.codeproject.com/csharp/pacanal.aspA tool to cha…