jQuery 如何用jquery完成每一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27043699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Jquery each complete
提问by Baha Ad?yaman
I did not do the complete in $.each(). how this is done ? Please help me
我没有在 $.each() 中完成。这是怎么做的?请帮我
$("element").each(function (i, v) {
//No problem
}, function () {
//How to complete finished ??
// alert(each finish);
})
回答by Brewal
To execute code after the each
loop is over :
在each
循环结束后执行代码:
var count = $("element").length;
$("element").each(function (i) {
// loop
if (i+1 === count) {
// this will be executed at the end of the loop
}
});
回答by Kevin Leary
The promise()
method is usually for AJAX, but it can be used with each()
to achieve what you want:
该promise()
方法通常用于 AJAX,但它可以用于each()
实现您想要的:
$('.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.');
});
回答by Denis Stoliarchuk
You can simply use $.when( $.each() ).then(myFunc, failFunc);
你可以简单地使用 $.when( $.each() ).then(myFunc, failFunc);
回答by Terry
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:
只需检查元素的索引i
, 以及.each()
循环末尾的元素数。如果匹配,那么您就完成了循环:
$('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
}
});
回答by Wim Pruiksma
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');
});
回答by Wim Pruiksma
$(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)
})
})
回答by Bill Criswell
Just put what you want to do after the .each
call. You're over thinking it.
只需在.each
通话后放上您想做的事情即可。你想多了。
$('.el').each(function () {
$(this).something();
});
alert('Done');