等待条件为真,然后继续功能

时间:2018-08-07 17:55:55

标签: javascript loops if-statement checkbox filter

我有几个复选框。当我选中一个时,另一个取消选中。

每次执行此操作时,都会有一个功能检查复选框的长度是否等于1。

预期的行为是:如果等于1,则该函数必须继续执行;否则,它必须等待,直到达到。事实是,这些复选框花费了太多时间来取消选中。

所以,它只是忽略一切并继续...

功能如下:

  function unchecking(){
    // Here I uncheck the other checkboxes when a new one gets checked
    $('.checkbox').on('change', function() {
      $('.checkbox').not(this).prop('checked', false);  
    });

    // Then I loop
    $.each($('.checkFiltro:checkbox:checked'), function (i, checkbox){
      // I need something like this:
      if($('.checkFiltro:checkbox:checked') < 2){
        // Continue and do another thing
      } else {
        // Wait until condition is true
      }
    });
  }

PS:无法使用收音机。这不是我的项目,我无法将其结构从复选框更改为单选。

2 个答案:

答案 0 :(得分:1)

正如我评论的那样-您无需“等待”直到条件为真(选中了一个复选框)。每次更改任何复选框的状态时,您都可以测试该条件。

此代码段演示了如何执行此操作-在控制台中详细地告诉您发生了什么。只要选中了一个复选框,您就会看到它说“运行其余代码”

$('input[type=checkbox]').on('change', function(e) {
  console.log('\nchanged: ' + this.name + ' is checked: ' + this.checked);

  let allChecked = $('input[type=checkbox]:checked');

  console.log('number of boxes checked = ' + allChecked.length);
  console.log('now unchecking any other checked boxes');

  $('input[type=checkbox]').not(this).prop('checked', false);
  let nowChecked = $('input[type=checkbox]:checked');
  
  console.log('number of boxes now checked = ' + nowChecked.length);
  
  if (nowChecked.length === 1) {
    console.log("Run the rest of the code; here, or call a function")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Instructions, other controls, whatever
</div>
<div>
  <label for="box1">Box 1</label>
  <input type="checkbox" id="box1" name="box1">
  <label for="box2">Box 2</label>
  <input type="checkbox" id="box2" name="box2">
</div>
<div>
  More stuff following the checkboxes
</div>

但是... ...只会被选中为零或一个复选框-永远不会选中两个-因为在选中一个复选框时取消选中另一个复选框。 (好吧,我想如果在您的代码开始运行时已经检查了两个对象,那么最初可能会有两个)

我有一个fiddle,其中的“取消选中”行已被注释掉,您可以在其中看到选中0、1、2个框时发生的情况。

答案 1 :(得分:0)

因此,您的问题基本上是函数要在要评估的所有数据到达之前返回。

您可以通过使用计时器结构来等待结果。

function unchecking(){

    $('.checkbox').on('change', function() {
      $('.checkbox').not(this).prop('checked', false);  
    });

    var waitInterval = setInterval(function(){
        var count = 0 ;
         $.each($('.checkFiltro:checkbox:checked'), function (i, checkbox){
            count++;
         });
        if(count > 2){
            clearInterval(this);
            //do stuff here
        }
        //the interval will continue to ask for the no of checked boxes until it gets cleared at the if statement
    },0);

}

Ps。我尚未测试此代码,请让我知道它是否无法执行我认为会执行的操作,然后我将修复并重新发送:)