如何使用 jQuery queue() 循环触发一次操作

How to trigger an action once with a jQuery queue() loop

我有一个包含许多元素的 jQuery 对象,例如$('.items')。我让这些项目在 queue() 中进行一些处理,并且根据条件,我想更改一个变量。队列完成后,我想检查该变量并触发一个事件。我的问题是检查变量并在 内部 队列中执行某些操作将触发多次(对于正在循环的 jQuery 对象中的每个节点),并执行此操作 outside队列发生在队列完成之前,所以它没有捕获变量更新。

例如:

var triggered = false;

$('.items').addClass('doing-things').delay(500).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check conditions and change variable
  if ( someCondition ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) { 
    // This will be fired repeatedly in the loop, $('.items').length number of times
    console.log(triggered); 
  }
  next();
});

// Check after queue
if ( triggered ) { 
  // This will fire once, but will be false, because it will fire before the queue finishes (with delays)
  console.log(triggered); 
}

任何人都可以告诉我如何更新队列中的 triggered 变量,然后检查它并触发一个事件(或者在这个例子中,执行 console.log(triggered))一次吗?

编辑:Example fiddle here 用于调试。

而不是简单地检查 triggered 是否为 true您等待触发为真

演示

var triggered = false,
  $test1 = $('#test1'),
    $test2 = $('#test2');

$('.item').addClass('doing-things').delay(1000).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check a condition and change variable
  if ( !triggered ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) { 
    // This will be fired repeatedly in the loop, $('.items').length number of times
    $test1.append('<div>Fired</div>'); 
  }
  next();
});
triggerEvent();

function triggerEvent ()
{
   if( !triggered )
   {
     setTimeout( triggerEvent, 1000 );
   }
   else
   {
       $test2.append('<div>Fired</div>'); 
   }
}
.item {
  padding: 10px;
  margin: 10px;
  border: 2px solid #aaa;
}

.item.doing-things {
  border-color: #f00;
}

.test {
  padding: 20px;
  margin: 10px;
  background: #fff;
}

#test1 {
  border: 2px solid #0f0;
}

#test2 {
  border: 2px solid #00f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
<div class="item">D</div>

<div id="test1" class="test"></div>
<div id="test2" class="test"></div>