简体   繁体   English

无法触发 jquery 中的 onclick 事件

[英]Cant trigger onclick event in jquery

I can't toggle a div's class on clicking it in jquery我无法在 jquery 中单击它时切换 div 的 class

Expected Behavior: I want to add the close class to the hamburger menu so that it becomes a cross on clicking and want to display an overlay for mobile screens, but currently I just want to figure out how to trigger this onclick event.预期行为:我想将关闭的 class 添加到汉堡菜单中,以便它在点击时变成十字,并希望显示移动屏幕的覆盖图,但目前我只想弄清楚如何触发此 onclick 事件。

Here's the code I am using to do so:这是我用来执行此操作的代码:

$("#mobile-menu").click(function() {
  $(".icon").toggleClass("close");
  var x = document.getElementsByClassName("overlay")[0];
  if ($(".icon").hasClass("close")) {
    x.style.display = "block";
    $("body").addClass("modal-open");
  } else {
    x.style.display = "none";
    $("body").removeClass("modal-open");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mobile-menu">
  <div class="icon">
    <span class="line top"></span>
    <span class="line middle"></span>
    <span class="line bottom"></span>
  </div>
</div>
.line {
    position: absolute;
    height: 4px;
    width: 100%;
    background-color: black;
    border-radius: 30%;
    transition: cubic-bezier(0.26, 0.1, 0.27, 1.55) 0.35s;
  }
  .icon.close .top {
    transform: rotate(45deg);
    top: 48%;
  }
  .icon.close .middle,
  .icon.close .bottom {
    transform: rotate(-45deg);
    top: 48%;
  }

It looks like your element is not getting binded to the click function. You need to use document.ready to check the readiness and bind event.看起来您的元素没有绑定到点击 function。您需要使用 document.ready 检查准备情况和绑定事件。

Below is the working code snippet:下面是工作代码片段:

$(document).ready(function(){

  $("#mobile-menu").click(function() {
    $(".icon").toggleClass("close");
    var x = document.getElementsByClassName("overlay")[0];
    if ($(".icon").hasClass("close")) {
       x.style.display = "block";
       $("body").addClass("modal-open");
     } else {
       x.style.display = "none";
       $("body").removeClass("modal-open");
     }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM