javascript基础总结

页面关闭前的提示消息:
window.onbeforeunload = function(e){ return '请不要关闭!';}
窗口大小发生改变时触发:
window.onresize = function(){
    location.reload();
}
浮动固定位置广告:
window.onload = scorll;     
window.onscroll = scorll;
function scorll(){
    $('.float').css('left',100+parseInt(document.body.scrollLeft)+'px');
    $('.float').css('top',100+parseInt(document.body.scrollTop)+'px');
}
jQuery支持的默认事件:

blur()、change()、click()、dbclick()、error()、focus()、
keydown()、keypress()、keyup()、load()、
mousedown()、mousemove()、mouseout()、mouseover()、mouseup()、
resize()、scroll()、select()、submit()、unload()

都是小写的

一次性绑定事件:
$('p').one('click',function(){
    alert($(this).val())
})

jQuery绑定的事件event对象总是作为第一个参数传入的。

创建三天前的时间:
var ago3Day = new Date(Date.parse(new Date().toString()) - 86400000*3);

浏览器后退后重新发送json请求加载数据:

if(localStorage.getItem('state') == 1) {
    console.log(localStorage.getItem('state'))
    //重新加载数据
    jsonData(_page);
}

window.onbeforeunload = function () {
    localStorage.setItem('state', 1);
};
JSON对象与字符串的转换:
JSON.stringify(cityList):obj--->string

JSON.parse(cityList):    string--->obj
手机号码正则
!(/^1[34578]\d{9}$/.test(phone)
获取当前URL并编码
encodeURIComponent(window.location.href)
获取所有选中的checkbox值
var shortNoticeIds = [];
$('input[name="chk_item"]:checked').each(function () {
    shortNoticeIds.push(parseInt($(this).val()));
});
Ajax传递数组值,后台用数组对象接收
$.ajax({
    url:"userMessageSignReadAll",
    data:{"shortNoticeIds":shortNoticeIds},
    dataType:'JSON',
    type:'post',
    traditional: true,  //重点
    success:function(data){
        mui.toast("操作成功");
    }
});
Ajax传递数json对象,后台用javaBean对象接收
$.ajax({
    url:"userMessageSignReadAll",
    data:{"shortNoticeIds":shortNoticeIds},
    dataType:'JSON',
    type:'post',
    contentType: "application/json; charset=utf-8",   //重点
    success:function(data){
        mui.toast("操作成功");
    }
});

//后台用@RequestBody接收参数
定时任务
var timeoutFlag = false; //启动及关闭按钮
var timeout = 3*60*1000;  //定时器周期 120秒
function countMessage() {
    if (timeoutFlag) return;

    todoMethod();

    setTimeout(countMessage,timeout); //递归调用自己
}
Form转JSON
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
监听radio变化
<input name="TypeCd" type="radio" class="bankTypeRadio" value="1"/>
<input name="TypeCd" type="radio" class="bankTypeRadio" value="2"/>
$(function () {
    $('.bankTypeRadio').change(function () {
        var $value = $("input[name='TypeCd']:checked").val();
    });
});
时间格式化
Date.prototype.format = function (fmt) { 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.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;
}
菜单点击添加active class,并去除其他菜单的active
<ul id='nav'>
    <li>导航一</li>
    <li>导航二</li>
    <li>导航三</li>
</ul>

<script type="text/javascript">
$('#nav').click(function(e) {
    $(e.target).addClass('active').siblings('.active').removeClass('active');
});

//siblings的作用,获取同级元素中带.active的元素
</script>
访问iframe中的元素
var iFrameDOM = $("iframe#someID").contents();
//然后,就可以通过find方法来遍历获取iFrame中的元素了
iFrameDOM.find(".message").slideUp();
使用js缓存数据
 var cache = {};
 $.data(cache,'key','value'); //缓存数据
  //获取数据
 $.data(cache,'key');
遮罩功能
 //遮罩
function coverDiv(){
    var procbg = document.createElement("div"); //首先创建一个div
    procbg.setAttribute("id","mybg"); //定义该div的id
    procbg.style.background = "#000000";
    procbg.style.width = "100%";
    procbg.style.height = "100%";
    procbg.style.position = "fixed";
    procbg.style.top = "0";
    procbg.style.left = "0";
    procbg.style.zIndex = "500";
    procbg.style.opacity = "0.6";
    procbg.style.filter = "Alpha(opacity=70)";
    document.body.appendChild(procbg);
}
//取消遮罩
function hide() {
    /* document.getElementById('light').style.display="none"; */
    $("div[class='xucun_content']").hide();
    var body = document.getElementsByTagName("body");
    var mybg = document.getElementById("mybg");
    body[0].removeChild(mybg);
}
为无法加载的图片设置默认图片
$('img').on('error', function () {
  $(this).prop('src', 'img/broken.png');
});
JSONP请求
unction callback(res){  
    console.log(res);  
}  
$.ajax({  
    url: '',  
    type: 'GET',  
    dataType:'jsonp',  
    jsonp:'callback',  
    jsonpCallback:'callback',  
    success: function (res) {  
       console.log(res);  
    }  
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值