常用js方法收集

来源:互联网 发布:使用ip连接mysql数据库 编辑:程序博客网 时间:2024/04/19 13:06
//ajax相关脚本 var Ajax = {};/** * Ajax方法 该方法只适用于同步请求 *@param url: url路径 参数可放在这里也可放在para里。 *@param para: 传递参数 可为空, 不为空时 通过sent传值,可避ie下免传参数过多导致失败 参考:http://gbtan.iteye.com/blog/653314 *@return:json数据集或{"success":"false"} *@demo:    1、var oJson = Ajax.post("abc.aspx?id=3");   2、var oJson = Ajax.post("abc.aspx","id=3"); */Ajax.post = function(url,para){    try{        var _para = para || null;        var NewXml;        if(window.ActiveXObject){            try{NewXml=new ActiveXObject("Microsoft.XMLHTTP");}            catch(e){                try{NewXml=new ActiveXObject("msxml2.XMLHTTP");}                catch(ex){}            }        }else if(window.XMLHttpRequest){            NewXml=new XMLHttpRequest();        }        NewXml.open("POST", url, false);        NewXml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");        NewXml.onreadystatechange = function(){            if (NewXml.readyState == 4){                if (NewXml.status == 200){                }else if (NewXml.status == 404){                    alert("Request URL does not exist");                }else{                    alert("Error: status code is " + NewXml.status);                }            }        };        NewXml.send(_para);        return eval('(' + NewXml.responseText + ')');    }    catch(e){        //alert(e.message);alert(e.description);alert(e.number);alert(e.name);        return{"success":"false"}    }}    /** * 执行基本ajax请求,返回XMLHttpRequest * Ajax.Json(url,{ * async 是否异步 true(默认) * method 请求方式 POST or GET(默认) * data 请求参数 (键值对字符串或json对象) 例如: data : {name:'jack',age:20}, * success 请求成功后响应函数,参数为json对象 * failure 请求失败后响应函数,参数为json对象 * });*/var myAjax = function(){function Json(url,opt){if(document.getElementById("_div_loging")==null){        _div_loging = document.createElement("div");            _div_loging.className = "loading";            _div_loging.innerHTML = "正在加载...";            _div_loging.id="_div_loging";            document.body.appendChild(_div_loging);        }function fn(){}var async   = opt.async !== false,method  = opt.method || 'GET',encode  = opt.encode || 'UTF-8',data    = opt.data || null,success = opt.success || fn,failure = opt.failure || fn;method  = method.toUpperCase();if(data && typeof data == 'object'){//对象转换成字符串键值对data = _serialize(data);}if(method == 'GET' && data){url += (url.indexOf('?') == -1 ? '?' : '&') + data;data = null;}var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');xhr.onreadystatechange = function(){_onStateChange(xhr,success,failure);};xhr.open(method,url,async);if(method == 'POST'){xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=' + encode);}xhr.send(data);return xhr;}function _serialize(obj){var a = [];for(var k in obj){var val = obj[k];if(val.constructor == Array){for(var i=0,len=val.length;i<len;i++){a.push(k + '=' + encodeURIComponent(val[i]));}}else{a.push(k + '=' + encodeURIComponent(val));}}return a.join('&');}function _onStateChange(xhr,success,failure){if(xhr.readyState == 4){var s = xhr.status;if(s>= 200 && s < 300){document.body.removeChild(document.getElementById("_div_loging"));success(eval('(' + xhr.responseText + ')'));}else{failure(xhr);}}else{}}return {Json:Json};}();//将form元素按键值形式转换成对象返回function formToJSON(form){    var _json = '{';var el;for(var i = 0,len = form.elements.length;i < len;i++){el = form.elements[i];if(el.name == "" || el.disabled) continue;switch(el.tagName.toLowerCase()){case "fieldset":break;case "input":switch(el.type.toLowerCase()){case "radio":if(el.checked)_json+="\""+el.name+"\":\""+el.value+"\",";break;case "checkbox":if(el.checked){    _json+="\""+el.name+"\":\""+el.value+"\",";}break;case "button":break;case "image":break;default:_json+="\""+el.name+"\":\""+el.value+"\",";break;}break;case "select":if(el.multiple){for(var j = 0, lens = el.options.length;j < lens; j++){if(el.options[j].selected){        _json+="\""+el.name+"\":\""+el.options[j].value+"\",";}}}else{    _json+="\""+el.name+"\":\""+el.value+"\",";}break;default:_json+="\""+el.name+"\":\""+el.value+"\",";break;}}form = el = null;    return _json.substring(0, _json.length - 1) + '}';}//根据id获取对象$=function(_id){    return document.getElementById(_id)?document.getElementById(_id):_id;}//根据name获取对象$$=function(_name){    return document.getElementsByName(_name)?document.getElementsByName(_name):_name;}/** * 绑定select控件 *@param _selObj: 控件对象或 *@param _jsonObj: json数据集 *@param _text: 显示字段 *@param _value: 值字段 *@return:true or false *@throws 这个方法所抛出的异常 */fnBindSelect = function(_objSel,_jsonObj,_sText,_sValue){    _objSel=$(_objSel);    _objSel.options.length = 0;     if(_sText==null||_sText==""||_sValue==null||_sValue==""){ return false;}    if(_jsonObj.length == 0||_jsonObj==""){        _objSel.options[0] = new Option('===无===', '-1', 0, 0);    }else{        for (var i = 0; i < _jsonObj.length; i++) {            _objSel.options[i] = new Option(_jsonObj[i][_sText], _jsonObj[i][_sValue], 0, 0);        }    }}//js获取url参数值 paras:参数名称 如没值则返回""fnRequest = function(paras){     var url = location.href;     var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");     var paraObj = {}     for (i=0; j=paraString[i]; i++){         paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);     }     var returnValue = paraObj[paras.toLowerCase()];     if(typeof(returnValue)=="undefined"){         return "";     }else{         return returnValue;     } }//js页面跳转 _url:网址fnGetToUrl = function(_url){    window.location.href=_url;}//弹出对话框fnShowDialog = function(_url){    window.open(_url);}//判断字符串长度(中文为2字节)  fucCheckLength = function(strTemp){    var i,sum=0;       for(i=0;i<strTemp.length;i++){           if ((strTemp.charCodeAt(i)>=0) && (strTemp.charCodeAt(i)<=255)){            sum=sum+1;           }else{             sum=sum+2;        }    }    return sum;   }//判断是否为数字function IsNum(s){    if (s!=null && s!="")    {        return !isNaN(s);    }    return false;}/*** 去字符串前后空格*/String.prototype.Trim = function(){     return this.replace(/(^\s*)|(\s*$)/g, ""); } String.prototype.LTrim = function(){     return this.replace(/(^\s*)/g, ""); } String.prototype.RTrim = function(){     return this.replace(/(\s*$)/g, ""); } /*** 动态加载图片 ****///使用事例//var img = new EnhancedImage(_localUrl + retJson.Dayinfo.item[tmpId].JP,onImageLoad);//function onImageLoad(image){//    document.body.appendChild(image.image);//    alert("image loaded and the size is " + image.width + "*" + image.height);//}//img.load();function EnhancedImage(src,onLoaded){    var self = this;    this.src = src;    this.width = 0;    this.height = 0;    this.onLoaded = onLoaded;    this.loaded = false;    this.image = null;        this.load = function(){        if(this.loaded)            return;        this.image = new Image();        this.image.src = this.src;        function loadImage(){            if(self.width != 0 && self.height != 0){                clearInterval(interval);                self.loaded = true;                self.onLoaded(self);//将实例传入回调函数            }            self.width = self.image.width;//是number类型            self.height = self.image.height;        }        var interval = setInterval(loadImage,100);    }}/*** 时间对象的格式化; 格式为yyyy-MM-dd hh:mm:ss*/Date.prototype.format = function(format){    if(!format|| format == ""){        format = "yyyy年MM月dd";    }    var o = {        "M+" : this.getMonth()+1, //month        "d+" : this.getDate(),    //day        "h+" : this.getHours(),   //hour        "m+" : this.getMinutes(), //minute        "s+" : this.getSeconds(), //second        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter        "S" : this.getMilliseconds() //millisecond    }    if(/(y+)/.test(format))format=format.replace(RegExp.$1,(this.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;}/*** 时间对象的格式化;* @dateTime {string} 要格式化的日期字符串* @format   {string} 格式化字符 可为空*/function formatDateTime(temper,format){    var myDate = new Date(temper.replace(/[-]/g,'/'));    return myDate.format(format);//格式化时间}/*** 将字符串转换为js日期格式(new Date);* @dateTime {string} 要格式化的日期字符串*/function GetDateObj(temper){    var myDate = new Date(temper.replace(/[-]/g,'/'));    return myDate;}Date.prototype.addDay=function(num){     this.setDate(this.getDate()+num);     return this; } Date.prototype.addMonth=function(num){     var tempDate=this.getDate();     this.setMonth(this.getMonth()+num);     if(tempDate!=this.getDate()) this.setDate(0);     return this; } Date.prototype.addYear=function(num){     var tempDate=this.getDate();     this.setYear(this.getYear()+num);     if(tempDate!=this.getDate()) this.setDate(0);     return this; }Date.prototype.add = function(part,num){      var datecopy;      var ms = this.getTime();      num = parseInt(num);      switch(part){          case "ms":              ms +=  num;              break;          case "ss":              ms +=  1000 * num;              break;          case "mi":              ms +=  60 * 1000 * num;              break;          case "hh":              ms +=  60 * 60 * 1000 * num;              break;          case "dd":              ms +=  24 * 60 * 60 * 1000 * num;              break;          case "wk":              ms +=  7 * 24 * 60 * 60 * 1000 * num;              break;          case "mm":              datecopy = new Date(Date.parse(this));              datecopy.setFullYear(this.getFullYear() + Math.floor((this.getMonth() + num) / 12));              var mth = (this.getMonth() + num) % 12;              if(mth  < 0)mth +=  12;              datecopy.setMonth(mth);              break;          case "qq":              datecopy = new Date(Date.parse(this));              datecopy.setFullYear(this.getFullYear() + Math.floor((this.getMonth() + 3 * num) / 12));              var mth = (this.getMonth() + 3 * num) % 12;              if(mth  < 0)mth +=  12;              datecopy.setMonth(mth);              break;          case "yy":              datecopy = new Date(Date.parse(this));              datecopy.setFullYear(this.getFullYear() + num);              break;      }      if(datecopy == null)          return new Date(ms);      else          return datecopy;  } /* * (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig * Special thanks to Dan Webb's domready.js Prototype extension * and Simon Willison's addLoadEvent * * For more info, see: * http://www.thefutureoftheweb.com/blog/adddomloadevent * http://dean.edwards.name/weblog/2006/06/again/ * http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype * http://simon.incutio.com/archive/2004/05/26/addLoadEvent *  * * To use: call addDOMLoadEvent one or more times with functions, ie: * *    function something() { *       // do something *    } *    addDOMLoadEvent(something); * *    addDOMLoadEvent(function() { *        // do other stuff *    }); * */addDOMLoadEvent = (function(){    // create event function stack    var load_events = [],        load_timer,        script,        done,        exec,        old_onload,        init = function () {            done = true;            // kill the timer            clearInterval(load_timer);            // execute each function in the stack in the order they were added            while (exec = load_events.shift())                exec();            if (script) script.onreadystatechange = '';        };    return function (func) {        // if the init function was already ran, just run this function now and stop        if (done) return func();        if (!load_events[0]) {            // for Mozilla/Opera9            if (document.addEventListener)                document.addEventListener("DOMContentLoaded", init, false);            // for Internet Explorer            /*@cc_on @*/            /*@if (@_win32)                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");                script = document.getElementById("__ie_onload");                script.onreadystatechange = function() {                    if (this.readyState == "complete")                        init(); // call the onload handler                };            /*@end @*/            // for Safari            if (/WebKit/i.test(navigator.userAgent)) { // sniff                load_timer = setInterval(function() {                    if (/loaded|complete/.test(document.readyState))                        init(); // call the onload handler                }, 10);            }            // for other browsers set the window.onload, but also execute the old window.onload            old_onload = window.onload;            window.onload = function() {                init();                if (old_onload) old_onload();            };        }        load_events.push(func);    }})();/*** 截取字符串 区别汉字和英文* @name         {string} 要截取的字符串* @maxLength    {int} 截取长度 可为空 默认20*/function widthCheck(name, maxLength){    if(name==null||name==""){        return "";    }    if(!maxLength){    maxLength = 20;    }    if(name==null||name.length<1){    return ["", ""];    }    var w = 0;//字符串长度,一个汉字长度为2    var s = 0;//汉字个数    var p = false;//判断字符串当前循环的前一个字符是否为汉字    var b = false;//判断字符串当前循环的字符是否为汉字    var nameSub;    for (var i=0; i<name.length; i++) {       if(i>1 && b==false){       p = false;       }       if(i>1 && b==true){       p = true;       }       var c = name.charCodeAt(i);       //单字节加1       if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {        w++;        b = false;       }else {        w+=2;        s++;        b = true;       }       if(w>maxLength && i<=name.length-1){       if(b==true && p==true){       nameSub = name.substring(0,i-2)+"...";       }       if(b==false && p==false){       nameSub = name.substring(0,i-3)+"...";       }       if(b==true && p==false){       nameSub = name.substring(0,i-2)+"...";       }       if(p==true){       nameSub = name.substring(0,i-2)+"...";       }       break;       }    }    if(w<=maxLength){    return name;    }    return nameSub;}/*** json对象转换为字符串* @obj   {obj} json对象*/function jsonToString(obj){    var THIS = this;        switch(typeof(obj)){           case 'string':               return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';           case 'array':               return '[' + obj.map(THIS.jsonToString).join(',') + ']';           case 'object':                if(obj instanceof Array){                   var strArr = [];                   var len = obj.length;                   for(var i=0; i<len; i++){                       strArr.push(THIS.jsonToString(obj[i]));                   }                   return '[' + strArr.join(',') + ']';               }else if(obj==null){                   return 'null';               }else{                   var string = [];                   for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));                   return '{' + string.join(',') + '}';               }           case 'number':               return obj;           case false:               return obj;       }   }/**  方法:Array.remove(dx)*  功能:删除数组元素.*  参数:dx删除元素的下标.*  返回:在原数组上修改数组*/Array.prototype.remove=function(dx){    if(isNaN(dx)||dx>this.length){return false;}    for(var i=0,n=0;i<this.length;i++){        if(this[i]!=this[dx]){            this[n++]=this[i]        }    }    this.length-=1}/*** 字符串转换为json对象* @obj  {string} json字符串*/function stringToJSON(obj){       return eval('(' + obj + ')');   }//获取鼠标坐标//var mousePos = new mouseCoords(window.event);function mouseCoords(ev){       if(ev.pageX || ev.pageY){           return {x:ev.pageX, y:ev.pageY};       }       return {           x:ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,           y:ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop       };   }function CPos(x, y){    this.x = x;    this.y = y;}/** * 得到对象的相对浏览器的坐标 * var obj =  document.getElementById('divid')  * alert(GetObjPos(obj)['x']) //x坐标 * alert(GetObjPos(obj)['y']) //y坐标 */function GetObjPos(ATarget){    var target = ATarget;    var pos = new CPos(target.offsetLeft, target.offsetTop);    var target = target.offsetParent;    while (target){        pos.x += target.offsetLeft;        pos.y += target.offsetTop;        target = target.offsetParent    }    return pos;}//禁止嵌套事件穿透 将该方法用到事件方法内即可function CancelBubble(){    if (event.stopPropagation){        event.stopPropagation();//在基于firefox内核的浏览器中支持做法stopPropagation    }else{        event.cancelBubble = true;//基于ie的写法    }}/** * 添加事件到对象 * obj: html对象 * type:事件名称 例如click(去除前面on) * fn:  函数对象 * args:参数*/function addEventListener(obj,type,fn,args){    var eventHandler = fn;    if(args){        eventHander = function(e){            fn.call(args, e);        }    }    if (obj.attachEvent){        obj['e'+type+fn] = fn;        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}        obj.attachEvent('on'+type, obj[type+fn]);    } else        obj.addEventListener(type,fn,false);}/** * 移除事件 * obj: html对象 * type:事件名称 例如click(去除前面on) * fn:  函数对象*/function removeEventListener(obj,type,fn) {   if(obj.detachEvent){      obj.detachEvent('on'+type,obj[type+fn]);      obj[type+fn] = null;   }else      obj.removeEventListener( type, fn, false );}//将字符转换成10进制整型function parseInt10(n){return parseInt(n, 10);}//获取礼拜几根据指定日期function GetWeekName(_dateTime){    var day=[ "日", "一", "二", "三", "四", "五", "六"];    return "星期"+day[_dateTime.getDay()];}

原创粉丝点击