Home > Web Front-end > JS Tutorial > body text

Summarize common js functions and common techniques

高洛峰
Release: 2016-10-15 09:31:23
Original
1122 people have browsed it

Ajax request

jquery ajax function

I have encapsulated an ajax function myself, the code is as follows:

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);
        }
    });};// 使用方法:Ajax('/data.json', 'get', function(data) {
    console.log(data);});
Copy after login

jsonp method

Sometimes we need to use jsonp method for cross-domain, I also encapsulated a function:

function jsonp(config) {
    var options = config || {};   // 需要配置url, success, time, fail四个属性
    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oHead.appendChild(oScript);
    window[callbackName] = function(json) {  //创建jsonp回调函数
        oHead.removeChild(oScript);
        clearTimeout(oScript.timer);
        window[callbackName] = null;
        options.success && options.success(json);   //先删除script标签,实际上执行的是success函数
    };
    oScript.src = options.url + '?' + callbackName;    //发送请求
    if (options.time) {  //设置超时处理
        oScript.timer = setTimeout(function () {
            window[callbackName] = null;
            oHead.removeChild(oScript);
            options.fail && options.fail({ message: "超时" });
        }, options.time);
    }};// 使用方法:jsonp({
    url: '/b.com/b.json',
    success: function(d){
        //数据处理
    },
    time: 5000,
    fail: function(){
        //错误处理
    }       });
Copy after login

Commonly used regular verification expressions

Mobile phone number verification

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

ID card number verification

var exp = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
Copy after login

ip verification

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])$/;
Copy after login

Commonly used 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');});
Copy after login

Prevent bubbling

function stopBubble(e){
    e = e || window.event;  
    if(e.stopPropagation){
        e.stopPropagation();  //W3C阻止冒泡方法  
    }else {  
        e.cancelBubble = true; //IE阻止冒泡方法  
    }  }
Copy after login

Replace all replaceAll

var replaceAll = function(bigStr, str1, str2) {  //把bigStr中的所有str1替换为str2
    var reg = new RegExp(str1, 'gm');
    return bigStr.replace(reg, str2);}
Copy after login

Get Parameter value in browser url

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;};
Copy after login

Deep copy object

function cloneObj(obj) {
    var o = obj.constructor == Object ? new obj.constructor() : new obj.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;}
Copy after login

Array deduplication

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]);  //返回没被删除的元素
        }
    }
    return result;};
Copy after login

Judge whether array elements are repeated

var isRepeat = function(arr) {  //arr是否有重复元素
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
    }
    return false;};
Copy after login

Generate random numbers

function randombetween(min, max){
    return min + (Math.random() * (max-min +1));}
Copy after login

Manipulate cookies

own.setCookie = function(cname, cvalue, exdays){
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = &#39;expires=&#39;+d.toUTCString();
    document.cookie = cname + &#39;=&#39; + cvalue + &#39;; &#39; + expires;};own.getCookie = function(cname) {
    var name = cname + &#39;=&#39;;
    var ca = document.cookie.split(&#39;;&#39;);
    for(var i=0; i< ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == &#39; &#39;) c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return &#39;&#39;;};
Copy after login

Summary of knowledge and skills

Data types

underfined, null, 0, false, NaN, empty string. Their logical negation results are all true.

闭包格式

好处:避免命名冲突(全局变量污染)。

(function(a, b) {
    console.log(a+b);  //30})(10, 20);
Copy after login

截取和清空数组

var arr = [12, 222, 44, 88];
arr.length = 2;   //截取,arr = [12, 222];  
arr.length = 0;   //清空,arr will be equal to [].
Copy after login

获取数组的最大最小值

var numbers = [5, 45822, 120, -215];
var maxInNumbers = Math.max.apply(Math, numbers);   //45822
var minInNumbers = Math.min.apply(Math, numbers);   //-215
Copy after login

浮点数计算问题

0.1 + 0.2 == 0.3   //false
Copy after login

为什么呢?因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示。可以通过使用toFixed()来解决这个问题。

数组排序sort函数

var arr = [1, 5, 6, 3];    //数字数组
arr.sort(function(a, b) {
    return a - b;   //从小到大排
    return b - a;   //从大到小排
    return Math.random() - 0.5;   //数组洗牌
});
Copy after login
var arr = [{   //对象数组
    num: 1,
    text: &#39;num1&#39;
}, {
    num: 5,
    text: &#39;num2&#39;
}, {
    num: 6,
    text: &#39;num3&#39;
}, {
    num: 3,
    text: &#39;num4&#39;
}];   
arr.sort(function(a, b) {
    return a.num - b.num;   //从小到大排
    return b.num - a.num;   //从大到小排
});
Copy after login

对象和字符串的转换

var obj = {a: &#39;aaa&#39;, b: &#39;bbb&#39;};
var objStr = JSON.stringify(obj);    // "{"a":"aaa","b":"bbb"}"
var newObj = JSON.parse(objStr);     // {a: "aaa", b: "bbb"}
Copy after login

git笔记

git使用之前的配置

1.git config --global user.email xxx@163.com
2.git config --global user.name xxx
3.ssh-keygen -t rsa -C xxx@163.com(邮箱地址)      // 生成ssh
4.找到.ssh文件夹打开,使用cat id_rsa.pub    //打开公钥ssh串
5.登陆github,settings - SSH keys  - add ssh keys (把上面的内容全部添加进去即可)
Copy after login

说明:然后这个邮箱(xxxxx@gmail.com)对应的账号在github上就有权限对仓库进行操作了。可以尽情的进行下面的git命令了。

git常用命令

1、git config user.name  /  user.email     //查看当前git的用户名称、邮箱
2、git clone https://github.com/jarson7426/javascript.git  project  //clone仓库到本地。
3、修改本地代码,提交到分支:  git add file   /   git commit -m “新增文件”
4、把本地库推送到远程库:  git push origin master
5、查看提交日志:git log -5
6、返回某一个版本:git reset --hard 123
7、分支:git branch / git checkout name  / git checkout -b dev
8、合并name分支到当前分支:git merge name   /   git pull origin
9、删除本地分支:git branch -D name
10、删除远程分支: git push origin  :daily/x.x.x
11、git checkout -b mydev origin/daily/1.0.0    //把远程daily分支映射到本地mydev分支进行开发
12、合并远程分支到当前分支 git pull origin daily/1.1.1
13、发布到线上:
    git tag publish/0.1.5
    git push origin publish/0.1.5:publish/0.1.5
14、线上代码覆盖到本地:
    git checkout --theirs build/scripts/ddos
    git checkout --theirs src/app/ddos
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!