JavaScript:如何防止双击或禁用按钮

JavaScript: how to Prevent Double button click or disable the button

本文关键字:按钮 双击 何防止 JavaScript      更新时间:2024-06-03

我有一个网页,里面有多个用户信息详细信息。所以当我点击"完成"按钮(每个用户详细信息旁边都有"完成")时,它应该执行一些任务(例如,我在这里发送邮件),并在我再次重定向到同一页面后禁用该按钮。我该怎么做?有什么可能的建议吗?

[这是一个刀片模板,因为我正在制作laravel网络应用程序]

我的网页演示:

<html>
    <head> 
        <title> User Details </title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> 
    </head>
    <body>

<div class="container">
<h3> Student Details </h3>
      <table  class="table table-striped table-bordered"  id="example">
        <thead>
          <tr>
            <td>Serial No</td>
            <td>Student Name</td>
            <td>Stdunet Email</td>
            <td>Course Name</td>  
            <td>Phone Number</td>
          <td>Action</td>
        </tr>
        </thead>
        <tbody>
          <?php $i=1; ?>
        @foreach($user as $row)
        @if($row->courses()->first())
          <tr>
            <td>{{$i}}</td>
            <td>{{$row->name }}</td>
            <td>{{$row->email}}</td>
           <td>{{$row->courses()->first()->name}} </td>
            <td>{{$row->phone}}</td>
           <td>
               <a href="{{route('sendMail',$row->id)}}" class="btn btn-warning">Complete</a>                                        
            </td>
          </tr>
          <?php $i++; ?>
          @endif

        @endforeach
        </tbody>

      </table>
    </div>
    </body>
</html>

您可以使用jquery的.one()方法。

// prevent anchor to click 
$(document).ready(function() {
  var clickCtr = 0;  
  $("a.btn").click( function() {
    if(clickCtr > 0) {
      return false; 
    }
    clickCtr++;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="https://www.google.co.in" target="_blank" class="btn btn-warning">Complete</a>

因此,有几种方法可以处理您的问题。

客户端的一个简单方法是使用jQuery(因为您在HTML中导入了jQuery)来暂时禁用该按钮。

这里有一个例子:

$(document).ready(function () {
     clicked = false;
     $(".btn").on('click', function (event) {  
           if (!clicked) {
             clicked = true;
             $(".text").text("Clicked!");
             setTimeout(function(){ 
               clicked = false;
               $(".text").text("");
             }, 2000);
           } else {
              $(".text").text("Already clicked!");
           }
     });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="btn btn-warning">Complete</button>
<text class="text"></text>