javascript 常用的自定义方法

(1)在页面获取cookie

//get value of cookie  
com.whuang.hsj.getCookie=function(cookieKey){  
    var cookies = document.cookie ? document.cookie.split('; ') : [];  
  
    for (var i = 0, l = cookies.length; i < l; i++) {  
        var parts = cookies[i].split('=');  
        if(parts && parts.length>1){  
            if(parts[0]==cookieKey||com.whuang.hsj.trim(parts[0])==cookieKey){  
                //username1=;  
                return parts[1];  
            }  
        }  
    }  
    return '';  
} ;

应用场景:

window.οnlοad=function(){
    var loginName22=com.whuang.hsj.$$one("username");
    loginName22.focus();

    //cookie的key是'userEmail'  
    username1=com.whuang.hsj.getCookie('userEmail');  
  
    //alert("username1:"+username1);  
    var issave222=com.whuang.hsj.$$one("issave");  
    if(username1 && username1!='' && username1!=null &&username1!=undefined){  
        loginName22.value=username1;  
        issave222.checked=true;  
    }else{  
        issave222.checked=false;  
    }  
    
}

wKiom1RHJVvzUoxuAADcoecOIvk918.jpg

(2)startWith和endWith

com.whuang.hsj.startWith=function(str,regex){
    return str.indexOf(regex)==0;
};
com.whuang.hsj.startsWith=com.whuang.hsj.startWith;
com.whuang.hsj.endWith=function(str,regex){
    return str.lastIndexOf(regex)==str.length-regex.length;
};
com.whuang.hsj.endsWith=com.whuang.hsj.endWith;

com.whuang.hsj.endWithArray=function(str,array2){
    for ( var i = 0; i < array2.length; i++) {
        var arrOne = array2[i];
        if(com.whuang.hsj.endsWith(str,arrOne)){
            return true;
        }
    }
    return false;
};

应用场景:上传图片时校验后缀名

var suffix22=['jpg','png','gif','Jpeg'];
        if(!com.whuang.hsj.endWithArray(uploadFile.value,suffix22)){
            alert("后缀名不对");
            return false;
        }

(3)设置错误信息(取代alert)

/***
error message
*/
com.whuang.hsj.setErrorMessage=function(obj,spanId,message,isBig){
     if(obj.focus){//if include focus method
         obj.focus();
     }
     
     var leaveMessageResultSpan;
     if (typeof spanId == 'string') {//if argument "spanId" just is a String
        leaveMessageResultSpan=com.whuang.hsj.$$id(spanId);
     }else{
         leaveMessageResultSpan=spanId;
     }
     var styleClass;
     if(isBig){
         styleClass='errormessageBig';
     }else{
         styleClass='errormessage';
     }
     // leaveMessageResultSpan.innerHTML="<span class='"+styleClass+"' >"+message+"</span>";
     leaveMessageResultSpan.innerHTML=message;
     leaveMessageResultSpan.className=styleClass;
     function cleanUp22(){
         leaveMessageResultSpan.innerHTML="";
      }
      setTimeout(cleanUp22,6000);
};

应用场景:校验表单

var username22=com.whuang.hsj.$$one("username");
    /*if(!com.whuang.hsj.isHasValue( username22.value)){
        username22.focus();
        leaveMessageResultSpan.innerHTML="<span class='errormessageBig' >请填写您的姓名.</span>";
                   function cleanUp22(){
                       leaveMessageResultSpan.innerHTML="";
                    }
                    setTimeout(cleanUp22,3000);
                    return false;
    }*/
    var companyObj=com.whuang.hsj.$$one("company");
    if(!com.whuang.hsj.checkNullValue(companyObj,'leaveMessageResult','请填写您的单位名称.')){
        return ;
    }
    if(!com.whuang.hsj.checkNullValue(username22,'leaveMessageResult','请填写您的姓名.')){
        return ;
    }
    
    var phoneObj=com.whuang.hsj.$$one("email");
    if(!com.whuang.hsj.checkNullValue(phoneObj,'leaveMessageResult','请填写您的电话.')){
        return ;
    }

    var object22=com.whuang.hsj.$$one("object");
    if(!com.whuang.hsj.checkNullValue(object22,'leaveMessageResult','请填写留言主题.')){
        return ;
    }
    
    var content22=com.whuang.hsj.$$one("content");
    if(!com.whuang.hsj.checkNullValue(content22,'leaveMessageResult','请填写留言内容.')){
        return ;
    }
    if(content22.value.length<10){
        com.whuang.hsj.setErrorMessage(content22,"leaveMessageResult","你的留言内容太短了.");
        return;
    }
    
    if(content22.value.length>5000){
        com.whuang.hsj.setErrorMessage(content22,"leaveMessageResult","你的留言内容太长了.");
        return;
    }

e90f7b50-ccce-3419-820f-8752e2bc5154.jpg

错误信息过6秒钟会自动消失

 

(4)动态增加下拉框

function showProductSmallClass(osType,smallId,projectPath)
{
    var abc44=function (obj) {
//        alert(obj);
        var jsonObj2=eval("("+obj+")");
        //alert(obj)
        var productSmallClass_div_id= com.whuang.hsj.$$id("productSmallClass_div_id");
        var html="<select  name='smallClass.id'>";
         html+="<option  value=\'-1\' text=\'--请选择--\' >--请选择--</option>";
        for(osvId in jsonObj2){
            //alert(osvId);
            var osvVersion=jsonObj2[osvId];
            html+="<option ";
            if(smallId&&smallId!=undefined && smallId!='' && smallId==osvId){
                html+="selected=\"selected\" ";
            }
            html+=" value=\'"+osvId+"\' text=\'"+osvVersion+"\' id='productSmallClass_"+osvId+"\'>";
            html+=osvVersion+"</option>";
         }
        html+="</select>";
        productSmallClass_div_id.innerHTML=html;
    };
    if(projectPath.lastIndexOf('/')!=projectPath.length-1){
        projectPath=projectPath+"/";
    }
    var url2=projectPath+"productSmallClass/json";
    //alert(url2);
    var xmlhw5=new XMLHttpHuangWei(url2, "productItemclassId="+osType,abc44);
    xmlhw5.XMLGetMethod();

}

(5)动态增加一个按钮,并指定click响应事件

com.whuang.hsj.addButton = function(parent22, onClickMethod) {
    var newInput = document.createElement("input");
    newInput.type = "button";
    buttonTd.appendChild(newInput);
    newInput.onclick = onClickMethod;
    return newInput;
};

(6)判断是否是数字

/***
* whether is digit,1.2 is allowed
*/
com.whuang.hsj.isNumber=function(int22){
    if(!int22 || int22==undefined){
        return false;
    }
    if( int22.match(/^[\d\\.]+$/i)){ 
    return true;
  }else{
    return false;
  }
};
/***
* whether is Integer,1.2 is not allowed
*/
com.whuang.hsj.isInteger=function(int22){
    if(!int22 || int22==undefined){
        return false;
    }
    if( int22.match(/^[\d]+$/i)){ 
    return true;
  }else{
    return false;
  }
};

应用:

var qrcodeSizeObj=com.whuang.hsj.$$id('qrcodeSize');
    var qrcodeSizeint=qrcodeSizeObj.value;
    if(!com.whuang.hsj.isHasValue(qrcodeSizeint)){
        qrcodeSizeObj.focus();
        alert('请输入像素大小.');
        return ;
    }
    var isDigit=com.whuang.hsj.isInteger(qrcodeSizeint);
    if(!isDigit){
        qrcodeSizeObj.focus();
        alert('请输入数字[100-1000]');
        return;
    }

(7)contains方法

contains=function(source,key2){
    var isDownload=(source.indexOf(key2)>-1);
    if(isDownload){
        return true;
    }else{
        return false;
    }
}

(8)使用this获取元素本身

<img src="a.jpg" height="160px"  width="250px"  οnclick="viewBigPic(this,event)" />
function viewBigPic(img333,event){
                    imgSrc=img333.src;
                    // alert(imgSrc);
                    var moveTop22 = parseInt(img333.offsetHeight  );
                    var moveLeft22 = parseInt(img333.offsetLeft );
                    // alert(moveTop22+"  ,  "+moveLeft22);
                    showLoadPanel(imgSrc,moveTop22,moveLeft22);
                }

(9)页面加载完成之后,文本框自动聚焦

window.οnlοad=function(){
        var title22=com.whuang.hsj.$$one("title");
         if(title22){
            title22.focus();
        }
    }

(10)使用javascript 如何缩放图片呢?

先看一下效果

410a95d0-f4e0-3a4a-9b46-82a7c55f31fd.jpg

点击"缩放",效果如下:

01974f2f-e347-3ebb-962b-856dfa901e66.jpg

页面代码:

                            <span style="float:left"> <a href="javascript:com.whuang.hsj.scale22(true,'company_module_pic');">放大</a>&nbsp;&nbsp;|&nbsp;&nbsp;
<a href="javascript:com.whuang.hsj.scale22(false,'company_module_pic');">缩小</a>
</span>
                        <img src="/yhyc/upload/p_w_picpath/20141016/20141016212719_312.jpg" id="company_module_pic" alt="轮播图" width="500">

说明:company_module_pic 是img标签的id

com.whuang.hsj.scale22 的实现:

/***
* 缩放图片
*/
com.whuang.hsj.scale22=function(isBig,company_module_pic){
    if (typeof company_module_pic == 'string') {
        company_module_pic=com.whuang.hsj.$$id(company_module_pic);
        if(company_module_pic==null ||company_module_pic==undefined){
            company_module_pic=com.whuang.hsj.$$one(company_module_pic);
        }
    }
    if(company_module_pic==null ||company_module_pic==undefined){
        return;
    }
    var oldWidth=company_module_pic.width;
    if(oldWidth==0){
        return;
    }
    var speed33=50;
    if(com.whuang.hsj.isHasValue(company_module_pic.src)){
        if(isBig){
            oldWidth+=speed33;
        }else{
            oldWidth-=speed33;
        }
        if(oldWidth>1300||oldWidth<400){
            alert("不能再缩放了");
            return;
        }
        company_module_pic.width=oldWidth;
    }
    

};

依赖的方法:

/*******************************************************************************
 * by id
 */
com.whuang.hsj.$$id = function(name22) {
    return document.getElementById(name22);
};
/***
 * if is radio ,please use com.whuang.hsj.$$arr
 * @param name22
 * @returns
 */
com.whuang.hsj.$$one = function(name22) {
    if (com.whuang.hsj.isHasValue(name22)) {
        var names222=document.getElementsByName(name22);
        //alert("names222:"+names222);
        //alert("typeof:"+(typeof names222 ));
        var className=Object.prototype.toString.call(names222);
        var boolean_isArray;
        var ieHtmlCollection='[object HTMLCollection]';
        if(isIEtest)//if browser is IE
        {
                 boolean_isArray=( className=== '[object Object]') ||(className=== ieHtmlCollection) ||names222 instanceof Array ;
        }else
        {
                 boolean_isArray=( className=== '[object Array]') ||(className=== '[object NodeList]'  )||(className==ieHtmlCollection)||names222 instanceof Array||names222 instanceof NodeList;
        }
        if(names222){
             if(boolean_isArray){
                     return names222[0];
             }else{
                     return names222;//why add [0] ??
            }
        }else{
            return "";
        }
    } else {
        return "";
    }
};
/**
 * whether has value
 * 
 * @param {Object}
 *            input
 */
com.whuang.hsj.isHasValue = function(input) {
    if (typeof input == "number" && input == "0") {
        return true;
    }
    if(!input)
    {
        return false;
    }
    if(input==""||input==undefined||com.whuang.hsj.isWholeWhitespace(input)){
        return false;
    }
    return true;
};
/**
 * is whitespace entirely
 * 
 * @param {Object}
 *            inputString
 */
com.whuang.hsj.isWholeWhitespace = function(inputString) {
    if (typeof inputString == "object") {
        return inputString;
    }
    var bootInit = true;
    if (inputString == "" || inputString == undefined) {
        return false;
    }
    for ( var i = 0; i < inputString.length; i++) {
        var c = inputString.charAt(i);
        if (!com.whuang.hsj.isWhitespace(c)) {
            bootInit = false;
            break;
        }
    }
    return bootInit;
};
com.whuang.hsj.isWhitespace = function(input) {// whether has whitespace
    var whitespace = " \t\n\r";
    for ( var i = 0; i < input.length; i++) {
        var c = input.charAt(i);
        if (whitespace.indexOf(c) >= 0) {
            return true;
        }
    }
    return false;
};

注意:

(1)com.whuang.hsj.scale22方法的第一个参数是boolean类型,必须是false或true;

第二个参数可以是img的id  ,也可以是img的name

(11)判断字符串是否包含句点

 var find = "\\.";//对句点要转义
                var reg = new RegExp(find, "g");
                var c = totalPriceStr.match(reg);
                    if(c){
                    alert("has .")
                       
              
                     }else{
                        alert("no . !!!") ;
                        }


参考:

http://hw1287789687.iteye.com/blog/2080411

http://hw1287789687.iteye.com/blog/2124945

http://hw1287789687.iteye.com/blog/2124996 

http://hw1287789687.iteye.com/blog/2144784