繁体   English   中英

如果在jquery中选中任何复选框,如何中断循环?

[英]How to break loop if any checkbox is checked in jquery?

这是我第一次使用 jquery,所以不要介意我!

我有一个 div 标签,里面有很多复选框和一个模态。 当页面第一次加载时,我想遍历 div 标签内的所有复选框,如果所有复选框都是空的(未选中),我想显示一个模式,但如果选中了这些复选框中的任何一个,模式将不会显示。

我试过这样

<div class="row" id="t-department-check">
   <h6><input type="checkbox" class="t-check">Work</h6>
   <h6><input type="checkbox" class="t-check">Stay</h6>
   <h6><input type="checkbox" class="t-check">Fun</h6>
   <h6><input type="checkbox" class="t-check">Go</h6>
</div>

<div id="department-modal"></div> <--my modal

<script>
      $(function () {
        $("#t-department-check .t-check").each(function () {
          if ($(this).is(":checked")) {
            $("#department-modal").modal("hide");
            console.log("Modal Hide");
            return false; // try to break the loop 
          }
          else if (!$(this).is(":checked")) {
            $("#department-modal").modal("show");
            console.log("Not yet");
            return true;
          }
        })
      });
    </script>

我的问题是,如果第二个或第三个或第四个复选框被选中,但第一个是空的,模态将显示出来,它会像这样打印到控制台

Not yet
Modal Hide
Not yet
Not yet

但是如果第一个复选框被选中并且其他是空的,则模式将保持隐藏状态并在控制台中像这样打印

Modal Hide

如果选中任何复选框,我想隐藏或使模态不显示。 我该如何解决?

其他上面做的方法是检查length复选框和长度checked复选框不等于0取决于这个hide()show()的模态

演示代码

 $(function() { //get length of checkbox var length = $("#t-department-check .t-check").length; console.log("length of checkboxes "+length) //get checked checkboxes length var checked_ = $("#t-department-check .t-check:checked").length console.log("length of checked "+checked_) //check if !0 if ((checked_ != 0) && (checked_ <= length)) { console.log("Modal Hide"); //hide your modal } else { //show your modal console.log("Not yet"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row" id="t-department-check"> <h6><input type="checkbox" class="t-check" >Work</h6> <h6><input type="checkbox" class="t-check" >Stay</h6> <h6><input type="checkbox" class="t-check" >Fun</h6> <h6><input type="checkbox" class="t-check" >Go</h6> </div> <div id="department-modal"></div> <--my modal

我认为唯一需要更正的是循环复选框的逻辑。 您需要首先完全循环所有复选框元素,然后决定是否显示模态。

$(function () {
        $("#t-department-check .t-check").each(function () {
          var showModal = true;
          $("#department-modal").modal("hide");
          if ($(this).is(":checked")) {
              showModal = false;
              return false; // try to break the loop 
          }else{
                  console.log("Modal Hide"); 
          }
 
        });

        if(showModal){
            $("#department-modal").modal("show");
            console.log("Not yet");          
          }
      });

暂无
暂无

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

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