简体   繁体   English

结合两个JS函数

[英]Combine two JS functions

Im currently trying to combine two if functions but somehow I only get errors.我目前正在尝试将两个 if 函数结合起来,但不知何故我只会得到错误。 I already tried multiple ways of combining them with no result.我已经尝试了多种组合它们的方法,但没有结果。

What I wanna do: I need to check if body has a specific class, if yes, a checkbox needs to be be unchecked.我想做的是:我需要检查 body 是否有特定的类,如果是,则需要取消选中复选框。

What I tried to combine:我试图结合的内容:

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

$(function() {
  $(document).on("click", function(e) {
    if ($(e.target).is(".main-nav-slideout") === false) {
      $("#main-nav-toggle").prop("checked", false);
    }
  });
});

My try on combining the snippets:我尝试结合片段:

$(function() {
  $(document).on("click", function(e) {
      if (document.body.classList.contains('thatClass')) && ($(e.target).is(".main-nav-slideout") === false) {
      $("#main-nav-toggle").prop("checked", false);
    }
  });
});

You could shorten it and just call the function when you need.您可以缩短它,并在需要时调用该函数。

 $(function() { checkCheckbox() $(document).on("click", '.main-nav-slideout', checkCheckbox) }); function checkCheckbox() { $("#main-nav-toggle").prop("checked", $('body').hasClass('thatClass')); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body class='thatClass'> <input type='checkbox' id='main-nav-toggle' /> <div class='main-nav-slideout'>Click me</div> </body>

Try this:试试这个:

$(function() {
  $(document).on("click", function(e) {
      if (document.body.getAttribute('class').split(' ').indexOf('thatClass')>-1 && ($(e.target).is(".main-nav-slideout") === false) {
      $("#main-nav-toggle").prop("checked", false);
    }
  });
});

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

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