开发中常用的一些JS代码片段

阻止默认行为

// 原生js
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.eventif (event.preventDefault){
        // w3c 阻止默认行为
        event.preventDefault();
    } else{
        // ie 阻止默认行为
        event.returnValue = false;
    }
}, false);

// jQuery
$('#btn').on('click', function (event) {
    event.preventDefault();
});

阻止冒泡

// 原生js
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.eventif (event.stopPropagation){
        // w3c方法 阻止冒泡
        event.stopPropagation();
    } else{
        // ie 阻止冒泡
        event.cancelBubble = true;
    }
}, false);

// jQuery
$('#btn').on('click', function (event) {
    event.stopPropagation();
});

验证码倒计时代码

<!-- dom -->
<input id="send" type="button" value="发送验证码">
// 原生js版本
var times = 60, // 临时设为60秒
    timer = null;

document.getElementById('send').onclick = function () {
    // 计时开始
    timer = setInterval(function () {
        times--;

        if (times <= 0) {
            send.value = '发送验证码';
            clearInterval(timer);
            send.disabled = false;
            times = 60;
        } else {
            send.value = times + '秒后重试';
            send.disabled = true;
        }
    }, 1000);
}

// jQuery版本
var times = 60,
    timer = null;

$('#send').on('click', function () {
    var $this = $(this);

    // 计时开始
    timer = setInterval(function () {
        times--;

        if (times <= 0) {
            $this.val('发送验证码');
            clearInterval(timer);
            $this.attr('disabled', false);
            times = 60;
        } else {
            $this.val(times + '秒后重试');
            $this.attr('disabled', true);
        }
    }, 1000);
});

常用的一些正则表达式

//匹配字母、数字、中文字符 
/^([A-Za-z0-9]|[\u4e00-\u9fa5])*$/ 

//验证邮箱 
/^\w+@([0-9a-zA-Z]+[.])+[a-z]{2,4}$/ 

//验证手机号 
/^1[3|5|8|7]\d{9}$/ 

//验证URL 
/^http:\/\/.+\./

//验证身份证号码 
/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/ 

//匹配中文字符的正则表达式 
/[\u4e00-\u9fa5]/ 

//匹配双字节字符(包括汉字在内) 
/[^\x00-\xff]/

js限定字符数(注意:一个汉字算2个字符)

<input id="txt" type="text">
//字符串截取
function getByteVal(val, max) {
    var returnValue = '';
    var byteValLen = 0;
    for (var i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/ig) != null) byteValLen += 2; else byteValLen += 1;
        if (byteValLen > max) break;
        returnValue += val[i];
    }
    return returnValue;
}

$('#txt').on('keyup', function () {
    var val = this.value;
    if (val.replace(/[^\x00-\xff]/g, "**").length > 14) {
        this.value = getByteVal(val, 14);
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值