Summary of common tool functions necessary for front-end development

Summary of common tool functions necessary for front-end development

1. Time formatting and other methods

It is recommended to use the moment.js library file

2. Use of template, loop, MAP and other methods

Methods of underscode.js

3. Serialize the form into JSON


Copy code
The code is as follows:

$.fn.serializeJson = function() {
var serializeObj = {};
var array = this.serializeArray();
var str = this.serialize();
$(array).each(function() {
if (serializeObj[this.name]) {
if ($.isArray(serializeObj[this.name])) {
serializeObj[this.name].push(this.value);
} else {
serializeObj[this.name] = [serializeObj[this.name], this.value];
}
} else {
serializeObj[this.name] = this.value;
}
});
return serializeObj;
};

4. String interception using ... filling


Copy code
The code is as follows:

String.prototype.strcut = function(number) {
var length = this.length;
var tmp = this.substr(0, number);
if (this.length > number) {
tmp += "…";
}
return tmp;
}

5. The time format is xxxx days, xxx minutes ago, date


Copy code
The code is as follows:

Date.prototype.Format = function(fmt, current) {
if (current) {
var diff = current - this.getTime();
if (diff < 5 * 60 * 1000) {
return "just now";
}
if (diff < 60 * 60 * 1000) {
return (Math.floor(diff / (60 * 1000))) + "minutes ago";
}
if (diff < 24 * 60 * 60 * 1000) {
return (Math.floor(diff / (60 * 60 * 1000))) + "hours ago";
}
if (diff < 30 * 24 * 60 * 60 * 1000) {
return (Math.floor(diff / (24 * 60 * 60 * 1000))) + "days ago";
}
if (diff < 12 * 30 * 24 * 60 * 60 * 1000) {
return (Math.floor(diff / (30 * 24 * 60 * 60 * 1000))) + "month ago";
}
if (diff > 12 * 30 * 24 * 60 * 60 * 1000) {
return (Math.floor(diff / (12 * 30 * 24 * 60 * 60 * 1000))) + "years ago";
}
}
var o = {
"Y+": this.getFullYear(), //Month
"M+": this.getMonth() + 1, //Month
"d+": this.getDate(), //day
"h+": this.getHours(), // hours
"m+": this.getMinutes(), // points
"s+": this.getSeconds(), // seconds
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() // milliseconds
};
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;
};

6. Parsing URLs


Copy code
The code is as follows:

function parseUrl() {
var arr = location.search.split('?')[1].split('&');
var params = {};
for (var i = 0, l = arr.length; i < l; i++) {
var param = arr[i].split('=');
params[param[0]] = param[1];
}
return params;
}

7. Get get parameters


Copy code
The code is as follows:

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

8. Function throttling makes frequent event triggers more sparse to improve performance, such as real-time search functions. The usage method is fn is the event response function, delay is the interval time, call throttle(fn, delay) to return a new function to the event


Copy code
The code is as follows:

function throttle(fn, delay) {
var timer = null;
return function() {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
}

9. Prevent multiple submissions of the form, as in 9, return a new function


Copy code
The code is as follows:

/**
* Prevent multiple clicks
*
* callback to be called when fn is completed
* function fn(event,end) {
* (typeof end === "function") && end(); // Operation completed
* }
*/function noRepeateTap(fn) {
var $obj;
return function(event) {
$obj = $(this);
if ($obj.data("loading") === "true") {
return;
}
$obj.data("loadding", "true").addClass('loadding');
fn.call(this, event, function end() {
$obj.data("loadding", "").removeClass('loadding');
return;
});
}
}

Example 9


Copy code
The code is as follows:

// Bind events
$(container).on('click', '.btn-cancel', noRepeateTap(cancel));
//Event response function
function cancel(event, end) {
event.preventDefault();
//Simulate asynchronous request
setTimeout(function(){
end(); // Need to manually call the injection completion function to notify completion. The function automatically adds the loading class class to adjust the style and automatically removes it after completion.
},5000)
}

<<:  Practical solution for Prometheus container deployment

>>:  SQL query for users who have logged in for at least n consecutive days

Recommend

Docker image compression and optimization operations

The reason why Docker is so popular nowadays is m...

Front-end advanced teaching you to use javascript storage function

Table of contents Preface Background Implementati...

Tips on MySQL query cache

Table of contents Preface Introduction to QueryCa...

Implementation of mysql backup strategy (full backup + incremental backup)

Table of contents Design scenario Technical Point...

How to modify mysql to allow remote connections

Regarding the issue of MySQL remote connection, w...

MySQL establishes efficient index example analysis

This article uses examples to describe how to cre...

Steps to solve the MySQL 8.0 time zone problem

Software Version Windows: Windows 10 MySQL: mysql...

How to set Nginx log printing post request parameters

【Foreword】 The SMS function of our project is to ...

Summarize some general principles of web design and production

<br />Related articles: 9 practical suggesti...

A brief analysis of the best way to deal with forgotten MySQL 8 passwords

Preface Readers who are familiar with MySQL may f...

How to deploy MySQL 5.7 & 8.0 master-slave cluster using Docker

> Deploy MySQL 5.7 cluster master & slave ...

HTML page adaptive width table

In the pages of WEB applications, tables are ofte...