问题
I did not do the complete in $.each(). how this is done ? Please help me
$("element").each(function (i, v) {
//No problem
}, function () {
//How to complete finished ??
// alert(each finish);
})
回答1:
To execute code after the each
loop is over :
var count = $("element").length;
$("element").each(function (i) {
// loop
if (i+1 === count) {
// this will be executed at the end of the loop
}
});
回答2:
The promise()
method is usually for AJAX, but it can be used with each()
to achieve what you want:
$('.element').each(function (key, val) {
console.log('Do something to each individual .element');
}).promise().done(function () {
console.log('Did things to every .element, all done.');
});
回答3:
You can simply use $.when( $.each() ).then(myFunc, failFunc);
回答4:
Simply check the index of the element, i
, with the number of element at the end of the .each()
loop. If it matches, then you are done with looping:
$('element').each(function (i, v) {
// Do all the stuff here
// Check if you are at the last item
if ($('element').length === i+1) {
// Code to execute when you are at the last item
}
});
回答5:
Maybe a late response. But this might come in handy There is a package that does what you want.
var myObject = { // or your array
1 : 'My first item',
2 : 'My second item',
3 : 'My third item'
}
Await.each(myObject, function(key, value){
//your logic here
});
Await.done(function(){
console.log('The loop is completely done');
});
回答6:
$(document).ready(function(){
let control = $(".container").find("#result");
const setPromise = new Promise(function(resolve,reject){
if(control.length){
resolve("Not Problem...")
}
else{
reject("WTF")
}
})
setPromise.then(function(answer){
console.log(answer)
}).catch(function(answer){
console.log(answer)
})
})
回答7:
Just put what you want to do after the .each
call. You're over thinking it.
$('.el').each(function () {
$(this).something();
});
alert('Done');
来源:https://stackoverflow.com/questions/27043699/how-to-jquery-each-complete