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

    xiaoxiao2021-04-03  29

    阻止默认行为

    // 原生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); } });
    转载请注明原文地址: https://ju.6miu.com/read-665960.html

    最新回复(0)