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

Rules for registration form design

I finished reading "Patterns for Sign Up &...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

CSS3+HTML5+JS realizes the shrinking and expanding animation effect of a block

When I was working on a project recently, I found...

Detailed steps for installing, configuring and uninstalling QT5 in Ubuntu 14.04

1. I downloaded QT5.13 version before, but after ...

How to use DCL to manage users and control permissions in MySQL

DCL (Data Control Language): Data control languag...

Native JS to implement click number game

Native JS implements the click number game for yo...

Comprehensive understanding of HTML basic structure

Introduction to HTML HyperText Markup Language: H...

Detailed explanation of the use of filter properties in CSS

The filter attribute defines the visual effect of...

MySQL 8.X installation tutorial under Windows

I had been using MySQL 5.7 before, but because My...

More than 100 lines of code to implement react drag hooks

Preface The source code is only more than 100 lin...

How to build YUM in Centos7 environment

1. Enter the configuration file of the yum source...

How to modify the location of data files in CentOS6.7 mysql5.6.33

Problem: The partition where MySQL stores data fi...