【问题标题】:click 1 times but alert multiple times in jquery在 jquery 中单击 1 次但多次提醒
【发布时间】:2020-03-12 13:48:14
【问题描述】:

我运行下面的代码,点击 open 5 次,然后点击 close 4 次,然后点击 alert。 我预计警报功能运行 1 次,但它运行 5 次 为什么?,如何防止这个问题?

代码包含3个按钮,点击open,显示两个按钮,包括closealert按钮,点击close 隐藏 alertclose 按钮,并通过点击 alert,alerts 1.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".close-but").css("display","none");
    $(".alert").css("display","none");
  $(".open-but").click(function(){
    $(".alert").click(function(){
        alert("1");
    });    
    $(".open-but").css("display","none");
    $(".close-but").css("display","flex");
    $(".alert").css("display","flex");
 });
 $(".close-but").click(function(){
    $(".close-but").css("display","none");
    $(".alert").css("display","none");
    $(".open-but").css("display","flex");
 });
});
</script>
</head>
<body>

  <button class="open-but">open</button>
  <button class="close-but">close</button>
  <br/>
  <button class="alert">alert</button>
</body>
</html>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    你放错了$(".alert").click()
    每次您点击.open-but 时,它都会为alert 按钮分配一个事件处理程序。您应该只分配一次$(".alert").click()。所以把它放在$(".open-but").click()之外,如下所示:

    <!DOCTYPE html>
    <html>
    
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
          $(document).ready(function() {
            $(".close-but").css("display", "none");
            
            $(".alert").css("display", "none");
            
            $(".open-but").click(function() {          
              
              $(".open-but").css("display", "none");
              $(".close-but").css("display", "flex");
              $(".alert").css("display", "flex");
            });
            
            $(".close-but").click(function() {
              $(".close-but").css("display", "none");
              $(".alert").css("display", "none");
              $(".open-but").css("display", "flex");
            });
            
            $(".alert").click(function() {
                alert("1");
              });
          });
    
        </script>
      </head>
    
      <body>
    
        <button class="open-but">open</button>
        <button class="close-but">close</button>
        <br />
        <button class="alert">alert</button>
      </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多