js限制按钮每隔一段时间才能再次点击

设置属性 disabled 可以限制交互,单击按钮时添加disabled=“disabled”属性,再为按钮添加定时器,一定时间后删除定时器和disabled属性

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 
11 <body>
12     <button id='but'> 发送 </button>
13
14     <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
15     <script>
16         $(function() {
17             $('#but').click(function() {
18                 $(this).attr("disabled", "disabled");
19                 var id = 10;
20                 //定时执行
21                 var timeing = setInterval(function() {
22                     id = id - 1;
23                     $('#but').html(id + 's');
24                 }, 1000);
25                 //延迟执行
26                 window.setTimeout(function() {
27                     //结束定时,恢复按钮可用
28                     clearInterval(timeing);
29                     $('#but').html('发送').removeAttr("disabled");
30                 }, 10000);
31             });
32         });
33     </script>
34 </body>
35 
36 </html>

或者用DOM

 1     <script>
 2         var but = document.getElementById('but');
 3         but.addEventListener('click', function() {
 4             var id = 10;
 5             var attr = document.createAttribute("disabled");
 6             attr.nodeValue = "disabled";
 7             //设置节点属性
 8             but.attributes.setNamedItem(attr);
 9             var timeing = setInterval(function() {
10                 id = id - 1;
11                 but.innerHTML = id + 's';
12             }, 1000);
13             window.setTimeout(function() {
14                 clearInterval(timeing);
15                 but.innerHTML = '发送';
16                 //移除节点属性
17                 but.attributes.removeNamedItem('disabled');
18             }, 10000);
19         });
20     </script>
posted @ 2019-12-14 15:02  umbed  阅读(1565)  评论(0编辑  收藏  举报