Summarize JS Common functions

Source: Internet
Author: User

I hope this article summarizes the content can give you crossing to bring a brand-fresh feeling. In addition, if you have any recommended JS skills, welcome to add in the comments, I can be stored in this article.


Ajax requests
jquery Ajax functions

I encapsulated an Ajax function myself with the following code:

var Ajax = function (URL, type success, error) {
$.ajax ({
Url:url,
Type:type,
DataType: ' JSON ',
timeout:10000,
Success:function (d) {
var data = D.data;
Success &&success (data);
},
Error:function (e) {
Error && error (e);
}
});
};
How to use:
Ajax ('/data.json ', ' Get ', function (data) {
Console.log (data);
});
Jsonp Way

Sometimes we want to use the Jsonp method for cross-domain, I also encapsulate a function:

function Jsonp (config) {
var options = Config | |   {}; Need to configure URL, success, time, fail four properties
var callbackname = (' Jsonp_ ' +math.random ()). Replace (".", "");
var ohead = document.getElementsByTagName (' head ') [0];
var oscript = document.createelement (' script ');
Ohead.appendchild (Oscript);
Window[callbackname] = function (JSON) {//Create JSONP callback function
Ohead.removechild (Oscript);
Cleartimeout (Oscript.timer);
Window[callbackname] = null;
Options.success &&options.success (JSON); Delete the script tag first, actually executing the success function
};
OSCRIPT.SRC = Options.url + '? ' + callbackname; Send Request
if (options.time) {//Set timeout processing
Oscript.timer = SetTimeout (function () {
Window[callbackname] =null;
Ohead.removechild (Oscript);
Options.fail &&options.fail ({message: "timeout"});
}, Options.time);
}
};
How to use:
Jsonp ({
URL: '/b.com/b.json ',
Success:function (d) {
Data processing
},
time:5000,
Fail:function () {
Error handling
}
});
Common regular-validation expressions

Mobile phone number Verification

var validate = function (num) {
var exp =/^1[3-9]\d{9}$/;
return exp.test (num);
};
Identification Number Verification

var exp =/^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16} ([0-9]|[ XX]) $/;
IP authentication

var exp =/^ (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) \. (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) \. (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) \. (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) $/;
Common JS functions

Back to Top

$ (window). Scroll (function () {
var a = $ (window). scrolltop ();
if (a > 100) {
$ ('. Go-top '). FadeIn ();
}else {
$ ('. Go-top '). FadeOut ();
}
});
$ (". Go-top"). Click (function () {
$ ("Html,body"). Animate ({scrolltop: "0px"}, ' 600 ');
});
Stop bubbling

function Stopbubble (e) {
E = e | | window.event;
if (e.stoppropagation) {
E.stoppropagation (); A way to block bubbles
}else {
E.cancelbubble = true; IE Block Bubbling method
}
}
Replace All ReplaceAll

var replaceall = function (Bigstr, str1, str2) {//Replace all bigstr in str1 with str2
var reg = new RegExp (str1, ' GM ');
Return Bigstr.replace (Reg, str2);
}
Get parameter values in the browser URL

var geturlparam = function (name) {
Return decodeURIComponent (New RegExp (' [? | &] ' + name + ' = ' + ' ([^&;] +?) (&|#|;| $) ', "IG"). EXEC (Location.search) | | [,""]) [1].replace (/\+/g, '%20 ')) | | Null
};
Deep Copy Objects

function Cloneobj (obj) {
var o = Obj.constructor = = Object? New Obj.constructor (): Newobj.constructor (Obj.valueof ());
for (var key in obj) {
if (O[key]! = Obj[key]) {
if (typeof (Obj[key]) = = = ' object ') {
O[key] =mods.cloneobj (Obj[key]);
}else{
O[key] =obj[key];
}
}
}
return o;
}
Array de-weight

var unique = function (arr) {
var result = [], JSON = {};
for (var i = 0, len = arr.length; i < Len; i++) {
if (!json[arr[i]]) {
Json[arr[i]] = 1;
Result.push (Arr[i]); Returns elements that have not been deleted
}
}
return result;
};
Determine if array elements are duplicated

var isrepeat = function (arr) {//arr If there are duplicate elements
var hash = {};
for (var i in arr) {
if (Hash[arr[i]]) return true;
Hash[arr[i]] = true;
}
return false;
};
Generate random numbers

function Randombetween (min, max) {
return min + (Math.random () * (Max-min + 1));
}
Manipulating cookies

Own.setcookie = function (CNAME, cvalue, exdays) {
var d = new Date ();
D.settime (D.gettime () + (exdays*24*60*60*1000));
var expires = ' expires= ' +d.toutcstring ();
Document.cookie = cname + ' = ' + Cvalue + '; ' + expires;
};
Own.getcookie = function (CNAME) {
var name = cname + ' = ';
var ca = Document.cookie.split (';');
for (var i=0; i< ca.length; i++) {
var c = Ca[i];
while (C.charat (0) = = ") c =c.substring (1);
if (C.indexof (name)! =-1) returnc.substring (name.length, c.length);
}
Return ';
};

Summary of Knowledge skills

Data type

underfined, NULL, 0, False, NaN, empty string. Their logical non-result is true.

Closing package format

Benefit: Avoid naming conflicts (global variable pollution).

(function (A, b) {
Console.log (A+B); 30
}) (10, 20);
Intercepting and emptying arrays

var arr = [12, 222, 44, 88];
Arr.length = 2; Intercept, arr = [12,222];
arr.length = 0; Empty, arr would beequal to [].
Gets the maximum minimum value of the array

var numbers = [5, 45822, 120,-215];
var maxinnumbers = Math.max.apply (Math, numbers); 45822
var mininnumbers = Math.min.apply (Math, numbers); -215
Floating point calculation problem

0.1 + 0.2 = = 0.3//false
Why is it? Because 0.1+0.2 equals 0.30000000000000004. JavaScript numbers are built on the IEEE 754 standard and are internally represented by 64-bit floating point decimals. You can solve this problem by using tofixed ().

Array sorting sort function

var arr = [1, 5, 6, 3]; Array of numbers
Arr.sort (function (A, b) {
return a-B; From small to large rows
return b-a; From the big to the small row
Return Math.random ()-0.5; Array Shuffle
});
var arr = [{//object array
Num:1,
Text: ' Num1 '
}, {
Num:5,
Text: ' Num2 '
}, {
Num:6,
Text: ' Num3 '
}, {
Num:3,
Text: ' Num4 '
}];
Arr.sort (function (A, b) {
return a.num-b.num; From small to large rows
return b.num-a.num; From the big to the small row
});
Conversion of objects and strings

var obj = {A: ' AAA ', B: ' BBB '};
var objstr = json.stringify (obj); "A": "AAA", "B": "BBB"} "
var newObj = Json.parse (OBJSTR); {A: "AAA", B: "BBB"}
Git notes

Git uses the previous configuration

1.git config--global user.email [email protected]
2.git config--global user.name xxx
3.SSH-KEYGEN-T rsa-c [email protected] (email address)//Generate SSH
4. Find the. SSH folder open, use cat id_rsa.pub//Open public key SSH string
5. Login to Github,settings-sshkeys-add SSH keys (add all the above contents)
Description: Then this email ([email protected]) corresponding account on GitHub has the right to operate the warehouse. The following GIT commands are available for you to enjoy.
Common git commands

1, git configuser.name/user.email//view the current git user name, mailbox
2, git clone Https://github.com/jarson7426/javascript.git project//clone warehouse to Local.
3, modify the local code, submit to the branch: git add file/git commit-m "Add File"
4. Push the local library to the remote library: Git push Origin master
5. View commit log: Git log-5
6. Return to a version: Git reset--hard 123
7. Branch: Git branch/git checkoutname/git checkout-b Dev
8. Merge Name branch to current branch: git merge Name/git pull origin
9. Delete local branch: git branch-d name
10. Delete Remote branch: Git push Origin:d aily/x.x.x
11. Git checkout-b mydevorigin/daily/1.0.0//Map The remote daily branch to the local Mydev branch for development
12. Merge remote branch to current branch Git pull Origin daily/1.1.1
13, published to the online:
git tag publish/0.1.5
Git push Origin publish/0.1.5:publish/0.1.5
14, online code coverage to the local:
git checkout--theirs Build/scripts/ddos
git checkout--theirs Src/app/ddos

Web Front end Learning Communication Group 21 598399936

Summarize JS Common functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.