• 封装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 engines
        var engine = {            
            ie: 0,
            gecko: 0,
            webkit: 0,
            khtml: 0,
            opera: 0,
    
            //complete version
            ver: null  
        };
        
        //browsers
        var browser = {
            
            //browsers
            ie: 0,
            firefox: 0,
            safari: 0,
            konq: 0,
            opera: 0,
            chrome: 0,
    
            //specific version
            ver: null
        };
    
        
        //platform/device/OS
        var system = {
            win: false,
            mac: false,
            x11: false,
            
            //mobile devices
            iphone: false,
            ipod: false,
            ipad: false,
            ios: false,
            android: false,
            nokiaN: false,
            winMobile: false,
            
            //game systems
            wii: false,
            ps: false 
        };    
    
        //detect rendering engines/browsers
        var 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 Safari
            if (/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 version
                var 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 Firefox
            if (/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 browsers
        browser.ie = engine.ie;
        browser.opera = engine.opera;
        
    
        //detect platform
        var 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 systems
        if (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 devices
        system.iphone = ua.indexOf("iPhone") > -1;
        system.ipod = ua.indexOf("iPod") > -1;
        system.ipad = ua.indexOf("iPad") > -1;
        system.nokiaN = ua.indexOf("NokiaN") > -1;
        
        //windows mobile
        if (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 version
        if (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 version
        if (/Android (d+.d+)/.test(ua)){
            system.android = parseFloat(RegExp.$1);
        }
        
        //gaming systems
        system.wii = ua.indexOf("Wii") > -1;
        system.ps = /playstation/i.test(ua);
        
        //return it
        return {
            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 }); });
  • 相关阅读:
    Mybatis实现数据的增删改查(CRUD)
    Spring MVC基础入门
    Swap in C C++ C# Java
    java和c#使用hessian通信
    基于Netty4的HttpServer和HttpClient的简单实现
    RabbitMQ的几种典型使用场景
    java多线程编程
    singleton pattern的推荐实现
    python多线程编程
    基于GMap.Net的地图解决方案
  • 原文地址:https://www.cnblogs.com/double405/p/5089196.html
Copyright © 2020-2023  润新知