一些我在开发中常用的代码段,方便自己copy,分享给大家,持续更新
JS延时执行一次setTimeout(function() {
//执行代码
}, 1500);
定时刷新,指定时间段执行(循环执行)
timer = setInterval(function() {
//执行代码
}, 1000);
JQuery版ajax请求
$.post("http://localhost/ajax.jsp?",
{
service:"txl",
pageNum:count
}
,function(result){
//处理代码
},"json");
动态创建css
//创建自定义的CSS
const css = document.createElement('style');
//隐藏,把优先级设置最高(!important)
css.innerText = '.wap-shadowbox{display:none!important;}';
document.head.appendChild(css);
fetch版ajax请求
fetch('/login.do', {
method: 'POST',
credentials: "include",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'userId=' + username + '&pass=' + pass + '&ABS_SchemeName=&valCode='
})
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(responseText => {
console.log(responseText);
})
.catch(e => {
console.log(e.toString());
})
fetch查询简版
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
fetch同步请求
async function fetchSync(url){
try{
let response= await fetch(url).then(r=>r.text());
console.log(response);
return response;
}catch(e){
console.log('网络请求异常:'+e);
}
}
JS获取时间戳
var timestamp = new Date().getTime();//返回数值单位是毫秒;
JS复制一个JSON对象
var newJson = JSON.parse(JSON.stringify(jsonData));
JSON对象转换成字符串
var jsonString = JSON.stringify(jsonData);
取随机数
Math.ceil(Math.random()*10); // 获取从1到10的随机整数 ,取0的概率极小。
Math.round(Math.random()); //可均衡获取0到1的随机整数。
Math.floor(Math.random()*10); //可均衡获取0到9的随机整数。
Math.round(Math.random()*10); //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
//因为结果在0~0.4 为0,0.5到1.4为1 ... 8.5到9.4为9,9.5到9.9为10。所以头尾的分布区间只有其他数字的一半。
日期格式化
function df(d,fmt) {
var o = {
"M+" : d.getMonth()+1, //月份
"d+" : d.getDate(), //日
"h+" : d.getHours(), //小时
"m+" : d.getMinutes(), //分
"s+" : d.getSeconds(), //秒
"q+" : Math.floor((d.getMonth()+3)/3), //季度
"S" : d.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (d.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
//调用方法:
var sjc= df(new Date(),"yyyy-MM-dd hh:mm:ss");
map实现数组删除
handleRemovePress = attrs => {
const {timers} = this.state;
this.setState({
timers: timers.filter(timer=>{
if (timer.id === attrs.id) {
return false;
}
return true;
}).map(timer => {
return timer;
}),
})
}