继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

前端常用代码片段(一)

于梦中
关注TA
已关注
手记 6
粉丝 43
获赞 134

前端常用代码片段系列

大部分需要引入 jquery-1.9.1.min.js(兼容ie8)

1.回车触发事件的代码

    $(function(){
        $('#username').focus();
        //回车查询
        document.onkeydown = function(event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if (e && e.keyCode == 13) {
                $("#signIn").trigger('click');
            }
        };
    });

2.把对象格式的参数转成键值对,并以&分割

/**
 * 把对象格式的参数转成键值对,并以&分割
 * @param arr 要转换的对象参数
 * @returns {string}
 */
function maiyaBuildParam(arr){
    var result = '';
    for(var key in arr)
    {
        result += key + "=" + encodeURIComponent(arr[key]) + "&";
    }
    result = result.substr(0,result.length-1);
    return result;
}

3.去除表单内容两端的空格,设置cookie缓存,对象转成字符串

 function submitForm() {
        var param = {
            userName: $.trim($("#username").val()),
            password: $.trim($("#password").val())
            //userName: $("#username").val().trim(),
            //password: $("#password").val().trim()
            //ie8下边支持$.trim,   不支持$("#").val().trim()
        };
        $.ajax({
            type: "post",
            url: serverIp + "rest/login?" + Math.random() + "&" + BuildParam(param),   
            //这里传入一个随机数避免ie8缓存问题,下边cache对ie8无效
            //data: JSON.stringify(param),  //传入组装的参数
            //contentType: "application/json; charset=utf-8",
            cache: false,  //禁用缓存
            dataType: "json",
            success: function (result) {
                if(result.result_code === '1'){
                    $.cookie('userinfo', JSON.stringify(result.data), { expires: 7 });
                    window.location.href = "index.html";
                }else{
                    alert('用户名或密码错误');
                }
            },
            error: function(msg) {
                alert(msg.message || '操作失败!');
            }
        })
    }

4.设置cookie,获取cookie

//设置cookie比,并将json数据源转成string
    $.cookie('userinfo', JSON.stringify(json), { expires: 7 });

//获取cookie,并将返回的string格式数据解析成json
    JSON.parse($.cookie('userinfo'));

//清除cookie
    $.cookie('userinfo',null);

项目示例

//设置cookie
 $.ajax({
            type: "post",
            url: serverIp + "rest/login?" + Math.random() + "&" + maiyaBuildParam(param),
            dataType: "json",
            success: function (result) {
                if(result.result_code === '1'){
                    $.cookie('userinfo', JSON.stringify(result.data), { expires: 7 });
                    window.location.href = "index.html";
                }else{
                    alert('用户名或密码错误');
                }
            },
            error: function(msg) {
                alert(msg.message || '操作失败!');
            }
        })
//获取和清空cookie
    if(!$.cookie('userinfo')) {
        location.href="login.html";
    }
    $("#loginOut a").click(function () {
        $.cookie('userinfo',null);
    });
    var userinfo = JSON.parse($.cookie('userinfo'));
    if(userinfo) {
        var _src = userinfo.docPic ? userinfo.docPic : (userinfo.docSex == 2 ? 'images/women.png' : 'images/man.png');
        $('#userInfoImage').attr("src",_src)
        $('#username,#leftusername').html(userinfo.docName);
        $('#jobtitle').html(userinfo.docProfe);
        var docRole = userinfo.docRole == 0 && '医师' || '管理员';
        $('#loginuser').html(docRole);
    }
    if(userinfo.docRole == 0) {
        $('#menu-product').show();
        $('#menu-admin,#menu-tongji').hide();
    } else if(userinfo.docRole == 1) {
        $('#menu-product').hide();
        $('#menu-admin,#menu-tongji').show();
    }

说明:
jquery.cookie.js 只允许开发人员存入字符串,故用JSON.stringify(json)将json转换成string

补充:JSON.stringify与JSON.parse() [ 此类方法在低版本ie上需要引入json2.js ]

parse用于从一个字符串中解析出json对象,如
var str = '{"name":"huangxiaojian","age":"23"}'
JSON.parse(str)
-->
Object
age: "23"
name: "huangxiaojian"
__proto__: Object
注意:单引号写在{}外,每个属性名都必须用双引号,否则会抛出异常。

stringify()用于从一个对象解析出字符串,如
var a = {a:1,b:2}
JSON.stringify(a)
--->
结果:"{"a":1,"b":2}"

5.三目运算的另一种写法

var docRole = userinfo.docRole == 0 && '医师' || '管理员';

var _src = userinfo.docPic ? userinfo.docPic : (userinfo.docSex == 2 ? 'images/women.png' : 'images/man.png');

记得以前看过别人写的文章里提到有网易的面试题出现过区分 ||  &&联合使用时返回的结果,当时老记不住,现在有这个应该容易记了

6.时间格式化

使用方式

new Date().format('yyyy-MM-dd');  // "2017-02-18"

new Date().format('yyyy-MM-dd hh-mm-ss');  //
"2017-02-18 04-41-08"
new Date().format('yyyy-MM-dd hh/mm/ss');  //
"2017-02-18 04/41/18"
new Date().format('yyyy-MM-dd HH/mm/ss');  //
"2017-02-18 16/42/30"

new Date().format('yyyy-MM-dd E HH/mm/ss');
  //"2017-02-18 六 16/51/16"
new Date().format('yyyy-MM-dd EE HH/mm/ss');  //
"2017-02-18 周六 16/51/30"

new Date().format('yyyy-MM-dd EEE HH/mm/ss');  //
"2017-02-18 星期六 16/51/77"

源码

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //12小时
        "H+": this.getHours(), //24小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "日",
        "1": "一",
        "2": "二",
        "3": "三",
        "4": "四",
        "5": "五",
        "6": "六"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
    }
    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;
}

7.获取输入日期所在周或者前后某周的周一

使用方式

new Date();
  //Sat Feb 18 2017 17:35:25 GMT+0800 (中国标准时间)

getMonday( new Date(),-1);  //
Mon Feb 06 2017 17:40:45 GMT+0800 (中国标准时间)

getMonday( new Date());  //Mon Feb 13 2017 17:34:34 GMT+0800 (中国标准时间)

getMonday( new Date(),1);  //
Mon Feb 20 2017 17:34:43 GMT+0800 (中国标准时间)

源码

function getMonday(date, offset){
    var today=date || new Date();
    return new Date( today - ((today.getDay() ||7) -1  - (offset||0) *7 )  *864E5  );
}

//改进,获取输入日期所在周或者前后某周的任意某天
function getWeekAnyday(weekday,offset,date){
    var today=date || new Date();
    return new Date( today - ((today.getDay() ||7) -(weekday||0)  - (offset||0) *7 )  *864E5  );
}

8.获取输入日期的前后某天日期

使用方式

new Date();
  //Sat Feb 18 2017 17:35:25 GMT+0800 (中国标准时间)

getOneDayByDate(new Date() ,-2);  //Thu Feb 16 2017 18:20:39 GMT+0800 (中国标准时间)

getOneDayByDate(new Date() ,2);  //Mon Feb 20 2017 18:20:49 GMT+0800 (中国标准时间)

源码

function getOneDayByDate(date, n) {
    var d = typeof date == 'string' && new Date(date) || date;
    d.setTime(d.getTime()+24*60*60*1000*n);
    //return d.getFullYear()+"-" + (d.getMonth()+1) + "-" + d.getDate();  //用于获取"2017-2-16"格式日期
    return new Date(d);
}

9.My97DatePicker使用

首先引入js

<script src="../My97DatePicker/WdatePicker.js"></script>

场景1:选择时间段,前者不能大于后者的时间,后者不能小于前者时间且不大于当天时间

<input type="text" onfocus="WdatePicker({maxDate:'#F{$dp.$D(\'datemax\')||\'%y-%M-%d\'}'})"   id="datemin" class="input-text">  -

<input type="text" onfocus="WdatePicker({minDate:'#F{$dp.$D(\'datemin\')}',maxDate:'%y-%M-%d'})" id="datemax" class="input-text">

给input赋相差一个星期的初始值

 $("#datemin").val(getOneDayByDate(new Date(), -6).format('yyyy-MM-dd'));
 $("#datemax").val(thisDate());

function thisDate() {
    var d = new Date();
    return d.format('yyyy-MM-dd');
}

10.刷新当前页面

//刷新当前页面

 location.reload();

//如果把该方法的参数设置为 true,那么无论文档的最后修改日期是什么,它都会绕过缓存,从服务器上重新下载该文档。这与用户在单击浏览器的刷新按钮时按住 Shift 健的效果是完全一样。

这是原生的方法


11. 判断元素是否在数组内

js方法

var arr = [1, 2, 3];
// js arr.indexOf(3)
var result1 = arr.indexOf(3); //返回index为2

jquery方法

var arr = [1, 2, 3];
// jquery $.inArray(3, arr)
var result = $.inArray(3, arr); //返回index为2

自定义方法

var arr = [1, 2, 3];
// 自定义 contains(arr, 3)方法
function contains(arr, obj) {
    //while
    var i = arr.length;
    while(i--) {
        if(arr[i] === obj) {
            return i;
        }
    }
    return -1;
}
var result1 = contains(arr, 3); //返回index为2

12.解析url中传递的参数

描述:解析ajax get方式传递的参数,
例如“https://www.zybuluo.com/mdeditor?url=https://www.zybuluo.com/static/editor/md-help.markdown

1.方法一

使用方式

    $.getUrlParam('url'); //"https://www.zybuluo.com/static/editor/md-help.markdown"

源码

$.getUrlParam = function(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = decodeURIComponent(window.location.search).substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
};

说明:此方式是将方法拓展到了jquery,也可以定义成方法

使用方式

    getUrlParam('url');  //"https://www.zybuluo.com/static/editor/md-help.markdown"
function getUrlParam(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = decodeURIComponent(window.location.search).substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
};
2.方法二将携带的所有参数转化成json对象

使用方式

var urlParamsToJson= getUrlParamsToJson(); //Object {url: "https://www.zybuluo.com/static/editor/md-help.markdown"}

源码

function getUrlParamsToJson() {
    var url = location.href;
    var nameValue;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {};
    for (var i = 0; nameValue = paraString[i]; i++) {
      var name = nameValue.substring(0, nameValue.indexOf("=")).toLowerCase();
      var value = nameValue.substring(nameValue.indexOf("=") + 1, nameValue.length);
      if (value.indexOf("#") > -1) {
         value = value.split("#")[0];
      }
      paraObj[name] = value;
    }
    return paraObj;
};

13.封装折叠(兼容ie8)

html

<ul id="Huifold1" class="Huifold">
  <li class="item">
    <h4>标题<b>+</b></h4>
    <div class="info"> 内容<br>很多内容 </div>
  </li>
  <li class="item">
    <h4>标题<b>+</b></h4>
    <div class="info"><img src="pic/2.png" ></div>
  </li>
  <li class="item">
    <h4>标题<b>+</b></h4>
    <div class="info"><img src="pic/1.png" ></div>
  </li>
</ul>

css

.Huifold .item{ position:relative}
.Huifold .item h4{margin:0;font-weight:bold;position:relative;border-top: 1px solid #fff;font-size:15px;line-height:22px;padding:7px 10px;background-color:#eee;cursor:pointer;padding-right:30px}
.Huifold .item h4 b{position:absolute;display: block; cursor:pointer;right:10px;top:7px;width:16px;height:16px; text-align:center; color:#666}
.Huifold .item .info{display:none;padding:10px}

js

jQuery.Huifold = function (obj, obj_c, speed, obj_type, Event,selected) {
    /*5个参数顺序不可打乱,分别是:相应区,隐藏显示的内容,速度,类型,事件*/
    //1 只打开一个,可以全部关闭
    //2 必须有一个打开
    //3 可打开多个
    //4全部打开
    var selected = selected ||"selected";
    if (obj_type == 2) {
        $(obj + ":first").find("b").html("-");
        $(obj_c + ":first").show();
    }
    if (obj_type == 4) {
        $(obj).find("b").html("-");
        $(obj_c).show();
    }
    if (obj_type == 5) {
        $(obj).find("b").html("-");
        $(obj_c).hide();
    }

    $(obj).on(Event, function () {
        // console.log("11111");
        if ($(this).next().is(":visible")) {
            if (obj_type == 2) {
                return false;
            }
            else {
                $(this).next().slideUp(speed).end().removeClass(selected);
                $(this).find("b").html("+");
            }
        }
        else {
            if (obj_type == 3 || obj_type == 4) {
                $(this).next().slideDown(speed).end().addClass(selected);
                $(this).find("b").html("-");
            } else {
                $(obj_c).slideUp(speed);
                $(obj).removeClass(selected);
                $(obj).find("b").html("+");
                $(this).next().slideDown(speed).end().addClass(selected);
                $(this).find("b").html("-");
            }
        }
    });
};

调用

$(function(){

     $.Huifold("#mealContainer>.item>.title", "#mealContainer>.item>.info", "fast", 4, "click");

});

14.封装tab页切换(兼容ie8)

html

<div id="tab_demo" class="HuiTab">
  <div class="tabBar clearfix"><span>选项卡一</span><span>选项卡二</span><span>自适应宽度</span></div>
  <div class="tabCon">内容一</div>
  <div class="tabCon">内容二</div>
  <div class="tabCon">内容三</div>
</div>

css

.clearfix:after{content:"\20";display:block;height:0;clear:both;visibility:hidden}.clearfix{zoom:1}
.tabBar {border-bottom: 2px solid #222}
.tabBar span {background-color: #e8e8e8;cursor: pointer;display: inline-block;float: left;font-weight: bold;height: 30px;line-height: 30px;padding: 0 15px}
.tabBar span.current{background-color: #222;color: #fff}
.tabCon {display: none}

js

jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i, callback) {
    var $tab_menu = $(tabBar);
    // 锟斤拷始锟斤拷锟斤拷锟斤拷
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();
    callback && callback(i);

    $tab_menu.on(tabEvent, function (event) {
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index = $tab_menu.index(this).toString();
        $(tabCon).hide();
        $(tabCon).eq(index).show();
        callback && callback(index);
        event.stopPropagation();
    });
};

调用

$(function(){

   $.Huitab("#tabbarSonFirst>.tabBar span", "#tabbarSonFirst>.tabCon", "current", "click", "0", loadChart);

});
// #tabbarSonFirst 父级id
// #tabbarSonFirst>.tabBar span控制条
// #tabbarSonFirst>.tabCon内容区
// current 选中tab样式
// click 事件 点击切换,可以换成mousemove 移动鼠标切换
// 1    默认第2个tab为当前状态(从0开始)
// callback 实现选中后再加载函数
function loadChart(i) {
    switch (i) {
        case '0'
            loopSportData();
            break;
        case '1'
            loopMealData();
            break;
        case '2':
            loadBloodPressureChart();
            break;
        default:
            break;
    }
}

15.正则校验Excel

 var reg = /^.*\.(?:xls|xlsx)$/i;//文件名可以带空格
if (!reg.test(path)) {//校验不通过
    alert("请上传excel格式的文件!");
    return;
}

16.正则表达式 数字和字母组合且必须含有一个

$pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/';

分开来注释一下:
^ 匹配一行的开头位置
(?![0-9]+$) 预测该位置后面不全是数字
(?![a-zA-Z]+$) 预测该位置后面不全是字母
[0-9A-Za-z] {6,10} 由6-10位数字或这字母组成
$ 匹配行结尾位置

17.低版本ie支持function.bind()

只需要添加一下代码,在需要的地方调用checkBind();就可以了

function checkBind()
{
    if (!Function.prototype.bind) {
        Function.prototype.bind = function(oThis) {
            if (typeof this !== "function") {
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }
            var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                fNOP = function() {},
                fBound = function() {
                    return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                        aArgs.concat(Array.prototype.slice.call(arguments)));
                };
            fNOP.prototype = this.prototype;
            fBound.prototype = new fNOP();
            return fBound;
        };
    }
}

18.标题栏闪动提示

来源:张鑫旭的博客文章

样式:图片描述

JS代码:
var titleInit = document.title, isShine = true;

setInterval(function() {
    var title = document.title;
    if (isShine == true) {
        if (/新/.test(title) == false) {
            document.title = '【你有新消息】';    
        } else {
            document.title = '【     】';
        }
    } else {
        document.title = titleInit;
    }
}, 500);

window.onfocus = function() {
    isShine = false;
};
window.onblur = function() {
    isShine = true;
};

// for IE
document.onfocusin = function() {
    isShine = false;
};
document.onfocusout = function() {
    isShine = true;
};

19.img图片垂直居中

<div id="box">
    <img src="images/demo.jpg" alt="" />
</div>
#box{
    width:500px;height:400px;
    text-align:center;
    border:1px solid #d3d3d3;background:#fff;
    display: table-cell;
    vertical-align:middle;

}

#box img{
    vertical-align:middle;
}

20.decodeURI() 函数解码处理不了"+"

使用javascript的decodeURIComponent函数解码查询字符串时,处理不了"+",例如下面

图片描述

这里需要再做一下处理:

decodeURIComponent(str.replace(/\+/g, '%20'));

即在调用decodeURIComponent函数之前要先把+替换为%20,这样就没有问题了

打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP