Code snippets summarized in this article (1)
Most need to introduce jquery
Last updated March 10, 2017
1. Enter trigger code
$(function(){ $('#username').focus(); //Carriage return query document.onkeydown = function(event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 13) { $("#signIn").trigger('click'); } }; });
2. Transform the parameters of the object format into key-value pairs and divide them by
/** * Converting the parameters of the object format into key-value pairs and dividing them by * @param arr Object parameters to be converted * @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. Remove the blanks at both ends of the form content, set the cookie cache, and convert the object into a string.
function submitForm() { var param = { userName: $.trim($("#username").val()), password: $.trim($("#password").val()) //userName: $("#username").val().trim(), //password: $("#password").val().trim() //ie8 supports $. trim below and $(""). val().trim() }; $.ajax({ type: "post", url: serverIp + "rest/login?" + Math.random() + "&" + BuildParam(param), //Here, a random number is passed in to avoid IE8 caching problem. The lower cache is invalid for ie8. //data: JSON.stringify(param), // parameters of the incoming assembly //contentType: "application/json; charset=utf-8", cache: false, //disable cache 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 Incorrect username or password'); } }, error: function(msg) { alert(msg.message || 'Operation failed!'); } }) }
4. Set cookies to get cookies
//Set cookie ratio and convert json data source to string $.cookie('userinfo', JSON.stringify(json), { expires: 7 }); //Get cookie s and parse the returned string format data into json JSON.parse($.cookie('userinfo')); //Clear cookie $.cookie('userinfo',null);
Project example
//Set 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 Incorrect username or password'); } }, error: function(msg) { alert(msg.message || 'Operation failed!'); } })
//Get and empty cookie s 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 && 'physician' || 'Administrators'; $('#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(); }
Explain:
jquery.cookie.js only allows developers to store strings, so JSON.stringify(json) is used to convert JSON to string.
Supplement: JSON.stringify and JSON.parse() [This method needs to introduce json2.js on low version ie]
Parse is used to parse json objects from a string, such as var str = '{"name":"huangxiaojian","age":"23"}' JSON.parse(str) --> Object age: "23" name: "huangxiaojian" __proto__: Object Note: Single quotation marks are written outside {}, and each attribute name must be double quotation marks, otherwise an exception will be thrown. stringify() is used to parse strings from an object, such as var a = {a:1,b:2} JSON.stringify(a) ---> Result: "{a":1","b":2}"
5. Another Writing Method of Trinomial Operations
Var docRole = userinfo. docRole = 0 & & &'Doctor'| |'Administrator'; var _src = userinfo.docPic ? userinfo.docPic : (userinfo.docSex == 2 ? 'images/women.png' : 'images/man.png'); I remember reading articles written by others before mentioning that there was a distinction in the test questions of Netease | & & the results returned when used in combination, but I always can't remember that at that time, it should be easy to remember that now.
6. Time Formatting
Usage mode
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-186616/51/16" new Date().format('yyyy-MM-dd EE HH/mm/ss'); // "2017-02-18 Saturday 16/51/30" new Date().format('yyyy-MM-dd EEE HH/mm/ss'); // "2017-02-18 Saturday 16/51/77"
Source code
Date.prototype.format = function (fmt) { var o = { "M+": this.getMonth() + 1, //Month "d+": this.getDate(), //day "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //12 hours "H+": this.getHours(), //24 hours "m+": this.getMinutes(), //branch "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //Millisecond }; var week = { "0": "day", "1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six" }; 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" : "week") : "") + 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. Get the week of the input date or the Monday of the week around it.
Usage mode
new Date(); //Sat Feb 18 2017 17:35:25 GMT+0800 (China Standard Time) getMonday( new Date(),-1); // Mon Feb 06 2017 17:40:45 GMT+0800 (China Standard Time) getMonday( new Date()); //Mon Feb 13 2017 17:34:34 GMT+0800 (China Standard Time) getMonday( new Date(),1); // Mon Feb 20 2017 17:34:43 GMT+0800 (China Standard Time)
Source code
function getMonday(date, offset){ var today=date || new Date(); return new Date( today - ((today.getDay() ||7) -1 - (offset||0) *7 ) *864E5 ); } //Improvement to get any day of the week in which the input date is entered or of the week around. function getWeekAnyday(weekday,offset,date){ var today=date || new Date(); return new Date( today - ((today.getDay() ||7) -(weekday||0) - (offset||0) *7 ) *864E5 ); }
8. Get the date of the day before and after the input date
Usage mode
new Date(); //Sat Feb 18 2017 17:35:25 GMT+0800 (China Standard Time) getOneDayByDate(new Date() ,-2); //Thu Feb 16 2017 18:20:39 GMT+0800 (China Standard Time) getOneDayByDate(new Date() ,2); //Mon Feb 20 2017 18:20:49 GMT+0800 (China Standard Time)
Source code
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 ();// Used to get the date in "2017-2-16" format return new Date(d); }
9.My97DatePicker uses
First introduce js
<script src="../My97DatePicker/WdatePicker.js"></script>
Scenario 1: Choose a time period, the former can not be greater than the latter, the latter can not be less than the former time and not more than the same day time.
<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">
Give input an initial value of a week's difference
$("#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. Refresh the current page
//Refresh location.reload(); //If the parameter of this method is set to true, it will bypass the cache and download the document from the server regardless of the last modification date of the document. This is exactly the same as holding down Shift Health when the user clicks the browser's refresh button.
This is the original method.
11. Analyzing the parameters passed in url
Description: Analyse the parameters passed by ajax get mode.
For example, " https://www.zybuluo.com/mdedi..."
1. method 1
Usage mode
$.getUrlParam('url'); //"https://www.zybuluo.com/static/editor/md-help.markdown"
Source code
$.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; };
Note: This approach extends the method to jquery and can also be defined as a method
Usage mode
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. Method 2 converts all parameters carried into json objects
Usage mode
var urlParamsToJson= getUrlParamsToJson(); //Object {url: "https://www.zybuluo.com/static/editor/md-help.markdown"}
Source code
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; };
12. Packaging folding (compatible with ie8)
html
<ul id="Huifold1" class="Huifold"> <li class="item"> <h4>Title<b>+</b></h4> <div class="info"> content<br>Many contents </div> </li> <li class="item"> <h4>Title<b>+</b></h4> <div class="info"><img src="pic/2.png" ></div> </li> <li class="item"> <h4>Title<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 The order of the parameters can not be disturbed. They are: corresponding area, hidden content, speed, type, event.*/ //Open only one and close all of them. //2 Must have an open //3 can open multiple //4 All open 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("-"); } } }); };
call
$(function(){ $.Huifold("#mealContainer>.item>.title", "#mealContainer>.item>.info", "fast", 4, "click"); });
13. Packaging tab page switching (compatible with ie8)
html
<div id="tab_demo" class="HuiTab"> <div class="tabBar clearfix"><span>Tab 1</span><span>Tab two</span><span>Adaptive width</span></div> <div class="tabCon">Content 1</div> <div class="tabCon">Content two</div> <div class="tabCon">Content three</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); // Rongjin Copy Start Rongjin Copy Rongjin Copy Rongjin Copy $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(); }); };
call
$(function(){ $.Huitab("#tabbarSonFirst>.tabBar span", "#tabbarSonFirst>.tabCon", "current", "click", "0", loadChart); }); // # tabbarSonFirst parent id // # tabbarSonFirst >. tabBar span control bar // # tabbarSonFirst >. tabCon content area // Currt checks tab style // click event click toggle, can be replaced by mousemove mobile mouse Toggle // 1 Default the second tab to be the current state (starting from 0) // callback implements the load function after selection function loadChart(i) { switch (i) { case '0' loopSportData(); break; case '1' loopMealData(); break; case '2': loadBloodPressureChart(); break; default: break; } }