梁小新blog

记录开发常用代码及方法

前言

日常开发,常常有一些方法、正则、表达式经常需要用到,在此记录,作为总结和方便查找。

函数类

简单的jQuery Ajax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function deleteCompany(companyId,callback) {
$.ajax({
type: 'POST',
url: '/make/company/deleteCompany',
data: {
companyId:companyId
},
dataType: "json",
success: function (result) {
callback(result);
},
error: function () {
}
});
},
毫秒数转日期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 创建日期转义
Date.prototype.format = function (format) {
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;
}
function formatDatebox(value) {
if (value == null || value == '') {
return '';
}
var dt;
if (value instanceof Date) {
dt = value;
} else {
dt = new Date(value);
}
return dt.format("yyyy-MM-dd"); //扩展的Date的format方法(上述插件实现)
}
//用法
formatDatebox(毫秒数);
拿到URL地址参数
1
2
3
4
5
6
7
// 拿到地址栏的参数 name为参数的名字
function getUrlParam(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r!=null) return unescape(r[2]); return null; //返回参数值
}
普通手机正则验证
1
2
3
4
5
6
7
function checkPhone(){
var phone = document.getElementById('phone').value;
if(!(/^1[34578]\d{9}$/.test(phone))){
alert("手机号码有误,请重填");
return false;
}
}

方法

js加减乘除出现多位小数点 例如:0.1+0.2 !== 0.3 0.30000000000000004

参考网址

http://madscript.com/javascript/javscript-float-number-compute-problem/

1
2
// 因为小数点相加会出现误差
var count = parseFloat((0.1+0.2).toFixed(10)); // count = 0.3
如何选中select选中的option
1
var companyName = $('#companyNameList').find("option:selected").text();
利用flex实现左边自适应,右边固定
1
2
3
4
5
6
7
.left {
flex-grow: 1
}
.right {
width: 200px;
flex-shrink: 0;
}

注意这里的 flex-grow 定义了内部元素未达到容器宽度时的处理方式,flex-shrink 则定义了超过外部容器宽度时内部元素的宽度处理方式。而且缺一不可,否则会在特殊情况下表现出错误的效果

常用loading效果

http://www.yyyweb.com/demo/inner-show/spinkit.html