JS常用备忘记录

来源:互联网 发布:java发送短信 编辑:程序博客网 时间:2024/05/18 02:37

JS常用备忘记录

JS遍历Json

————————————————————————

for(varkey injson){};



Ajax实现POST传值

————————————————————————

functionxmlHttpConect(){//连接函数
    try{
        xmlHttp = new XMLHttpRequest();
    }catch(trymicrosoft){
        try{
            xmlHttp=newActiveXObject("Msxml2.XMLHTTP");
        }catch(othermicrosoft){
            try{
                xmlHttp = newActiveXObject("Microsoft.XMLHTTP");
            }catch(failed){};
        };
    };
    if(!xmlHttp){
        info("Ajax初始化失败", '../_img/warning.png', '#f1c2cc');
    }
    returnxmlHttp;
};


function ajax(url, data){//异步发送
    this.http = xmlHttpConect();
    this.http.open('POST', url, true);
    this.http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    this.http.send(data);
}


//实例化,并处理返回结果
varaj = newajax('login.php', 'num=4')
aj.http.onreadystatechange = function(){
     if(aj.http.readyState==4){
         inf(aj.http.responseText);
     }
}



JS获取浏览器(客户端)信息

——————————————————————————

varinfo = navigator.userAgent;



JS处理透明度(兼容IE、FF、Opera、Chrome、Satari)

——————————————————————————

if(document.all)tag.filters.alpha.opacity = 50;  //IE内核 filters不可赋给style,直接赋给DOM对象

elsetag.style.opacity = 0.5;    //非IE内核



滚动窗口时使DIV位置不变

——————————————————————————

//主要针对IE6,其它浏览器可以使用position:fixed进行定位,效果远比JS控制要好

div.style.top = document.documentElement.scrollTop + (document.documentElement.clientHeight - div.clientHeight) + "px";



JS判断浏览器类型,并返回版本信息

——————————————————————————

function browserType(){
    var ua = navigator.userAgent.toLowerCase();
    var ie=false, firefox=false, chrome=false, opera=false, safari=false, info=ua;
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? ie = s[1] : 
    (s = ua.match(/firefox\/([\d.]+)/)) ? firefox = s[1] : 
    (s = ua.match(/chrome\/([\d.]+)/)) ? chrome = s[1] : 
    (s = ua.match(/opera.([\d.]+)/)) ? opera = s[1] : 
    (s = ua.match(/version\/([\d.]+).*safari/)) ? safari = s[1] : 0;
    return{
        info:info,  //客户端完整信息
        ie:ie,      //IE浏览器
        ff:firefox, //Firefox浏览器
        chr:chrome, //chrome浏览器
        op:opera,   //opera浏览器
        sa:safari   //safari浏览器
    };
}


JS取整

——————————————————————————

Math.round(0.5)=1;  //四舍五入
Math.ceil(2.001)=3;//进位
Math.floor(5.99)=5;//舍位


js 将json字符串转换为json对象(三种方式)

——————————————————————————

json = JSON.parse(str);

json = eval('(' + str + ')');

json = str.parseJSON();


//反之

str = json.toJSONString();

str = JSON.stringify(json);


参考资料:http://hi.baidu.com/cmoooo/item/a69c29c5c208823a98b498d6

原创粉丝点击