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

时间:2017-11-15 06:34:51

标签: javascript jquery jquery-queue

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

例如:

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进行调试。

1 个答案:

答案 0 :(得分:1)

而不是简单地检查triggeredtrue等待触发是真的

<强>演示

&#13;
&#13;
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>'); 
   }
}
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;