javascript 防止多次提交或执行(在规定时间段内只允许执行一次) 默认 3000ms

"use strict"

class Func{
    
    constructor(){}
        //防止多次提交或执行(在规定时间段内只允许执行一次) 默认 3000ms
    isRun(id, isExit, time){
        if(this.list === undefined){Func.prototype.list = {};}
        if(id === undefined){return "参数id未定义";}
        if(isExit === true){delete(this.list[id]); return "删除对象: "+id;}
        let o = this.list[id];
        if(!o){this.list[id] = {time:time || 3000, nowTime:new Date().getTime()}; return true;}
        let t = new Date().getTime() - o.nowTime;
        if(t < o.time){return o.time - t;}
        o.nowTime = new Date().getTime();
        return true;
    }

}

调用:

 1 //绑定事件
 2     v.addEvent(v.get("loginBoxId"), "click", (e)=>{
 3         let id = e.target.id;
 4         
 5         if(id === "BackId"){//返回按钮
 6             history.back();
 7             
 8         }else if(id === "RegisterId"){//注册按钮
 9             location.href = "../register/view.php";
10             
11         }else if(id === "LoginId"){//登录按钮
12             if(new Func().isRun("login0") !== true){console.log('停止'); return;}//防止连续提交
13             console.log('执行');
14             let el_err = v.get("errorId"), el_e = v.get("EmailId"), el_p = v.get("PasswordId");
15             if(!el_e.value || !el_p.value){el_err.innerHTML = "Please fill in email address and password!"; return;}
16             //把 用填写的邮箱地址和密码发送给login.php进行验证返回true 或false
17             new Ajax({
18                 url:"./login.php", 
19                 data:"data="+JSON.stringify([el_e.value, el_p.value]), 
20                 success:(data)=>{
21                     if(JSON.parse(data) === true){
22                         location.href = "../index.php";
23                         return;
24                     }
25                     el_err.innerHTML = "Illegal email or password!";
26                 }
27             });
28         }
29     });
View Code

展示:

猜你喜欢

转载自www.cnblogs.com/weihexinCode/p/12347185.html