JavaScript笔记(一),
加法函数
javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显
//调用:accAdd(arg1,arg2) //返回值:arg1加上arg2的精确结果 function accAdd(arg1,arg2){ var r1,r2,m; try{ r1 = arg1.toString().split(".")[1].length; }catch(e){ r1 = 0; } try{ r2 = arg2.toString().split(".")[1].length; }catch(e){ r2 = 0; } m = Math.pow( 10 , Math.max( r1 , r2 )); return ( arg1 * m + arg2 * m) / m ; }
获取当前项目的绝对路径
function getRealPath() { // 获取当前网址,如: http://localhost:8083/myproj/view/my.jsp var curWwwPath = window.document.location.href; // 获取主机地址之后的目录,如: myproj/view/my.jsp var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); // 获取主机地址,如: http://localhost:8083 var localhostPaht = curWwwPath.substring(0, pos); // 获取带"/"的项目名,如:/myproj var projectName = pathName .substring(0, pathName.substr(1).indexOf('/') + 1); // 得到了 http://localhost:8083/myproj var realPath = localhostPaht + projectName; return realPath; }
获取get方式传递的参数
function urlParamsByGet(){ var aQuery = window.location.href.split("?"); //取得Get参数 var params = new Array(); if(aQuery.length > 1) { var paramStr = aQuery[1].split("&"); for(var i=0, iLoop = paramStr.length; i<iLoop; i++) { var keyValue = paramStr[i].split("="); //分离key与Value params[keyValue[0]] = keyValue[1]; } } return params; }
将表单序列化为JSON数据
(function ($) { $.fn.serializeJson = function () { var serializeObj = {}; var array = this.serializeArray(); var str = this.serialize(); $(array).each(function () { if (serializeObj[this.name]) { if ($.isArray(serializeObj[this.name])) { serializeObj[this.name].push(this.value); } else { serializeObj[this.name] = [serializeObj[this.name], this.value]; } } else { serializeObj[this.name] = this.value; } }); return serializeObj; }; })(jQuery);