防止按钮在短期内被屡次点击屡次触发事件

如何防止在短期内屡次点击按钮屡次触发事件呢?javascript

个人解决方法是:设置一个延时器,就能够起到做用了。css

下面附上代码,方便往后回看。html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

<title>阻止屡次点击出发屡次事件</title>

<style type="text/css">

.btn{

background-color: #3377FF;

line-height: 50px;

color: #FFFFFF;

text-align: center;

margin: 100px auto;

}

</style>

</head>

<body>

<div class="btn">确认</div>

</body>

<script src="js/jquery-3.2.1.js"></script>

<script type="text/javascript">

var timer = null;

$('.btn').click(function(e){

if(timer != null){

clearTimeout(timer);

}

timer = setTimeout(function(){

touchBtn();

},1000);

})

function touchBtn(){

console.log('这是一个向服务器请求的方法');

}

</script>

</html>
相关文章
相关标签/搜索