I'm using the following code to delay a trigger looping through a list of li items
var eleID = '';
$('.SlideSelect').each(function(i) {
eleID = $(this).attr('id');
$('#'+eleID).delay(800*i).trigger('click');
});
However the delay does not work and just loops through.
Does anyone know why?
var eleID = '';
$('.SlideSelect').each(function() {
e开发者_JAVA百科leID = $(this).attr('id');
setTimeout(function(){
$('#'+eleID).trigger('click');
}, 5000)
});
Delay is used for the animation queue. If you want to delay anything else, you should use setTimeout. Note the use of a separate function to allow the capture of each value in the delayed function.
var eleID = '';
$('.SlideSelect').each(function(i) {
eleID = $(this).attr('id');
delayedTrigger( $('#'+eleID), 800*i );
});
function delayedTrigger(elem, delay)
{
setTimeout( function() { $(elem).trigger('click'); }, delay );
}
Only fx methods
do have an implicit impact on jQuerys internal queue. To have any other kind of method you explicitly need to call .queue()
:
$('#'+eleID).delay(800*i).queue(function( next ) {
$(this).trigger('click');
next();
});
This should work. The only thing I'm not so sure about is if this
points to the jQuery wrapped set of invocation. I leave it to you to find out right now.
Another problem which comes along with this solution are the closures of ECMAscript. Since you're going to call that code within a loop, all those anonymous function(-contexts) will close over the eleID
variable and reference it. To fix that, we need to invoke another context:
$('#'+eleID).delay(800*i).queue((function( myID ) {
return function( next ) {
$('#'+myID).trigger('click');
next();
};
}(eleID)));
.delay
functions on effects (and you are trying to delay something other than an effect).
Admittedly, the documentation isn't obvious about this, beyond .delay
being part of the Effects section.
Use setTimeout
instead, in the usual fashion.
You cannot use delay()
for that since it only works for effects.
$('.SlideSelect').each(function(i) {
window.setTimeout(function() {
$('#'+this.id).trigger('click');
}, 800*i)
});
var eleID = '';
var i=0;
$('.SlideSelect').each(function(event) {
eleID = $(this).attr('id');
$('#'+eleID).delay(800*i).trigger('click');
i++;
});
精彩评论