jQuery“each()”函数是同步的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7371942/
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
Is jQuery "each()" function synchronous?
提问by Saeed Neamati
consider this scenario for validating:
考虑这个场景来验证:
function validateForm (validCallback) {
$('#first-name').add($('#last-name')).add($('#address')).each(function () {
// validating fields and adding 'invalid' class to invalid fields.
});
// doing validation this way for almost 50 fields (loop over 50 fields)
if ($('#holder .invalid').length == 0) {
// submitting data here, only when all fields are validated.
}
}
Now, my problem is that, the ifblock get executed before loops are finished. I expected the body of validateForm
to be executed synchronously, but it seems that jQuery each()
function gets executed asynchronously. Am I right? Why this doesn't work?
现在,我的问题是,在循环完成之前执行if块。我期望validateForm
同步执行的主体,但似乎 jQueryeach()
函数是异步执行的。我对吗?为什么这不起作用?
回答by Abraham
Yes, the jQuery each
method is synchronous. Nearly ALL JavaScript is synchronous. The only exceptions are AJAX, timers (setTimeout
and setInterval
), and HTML5 Web Workers.
Your problem is probably somewhere else in your code.
是的,jQueryeach
方法是同步的。几乎所有的 JavaScript 都是同步的。唯一的例外是 AJAX、计时器(setTimeout
和setInterval
)和 HTML5 Web Workers。
您的问题可能在您的代码中的其他地方。
回答by ShankarSangoli
jQuery
is purely a javascript library. Except ajax
, setTimeout
and setInterval
there is nothing that can asynchronously executed in JavaScript
. So each
is definitely executed synchronously. There is definitely some js error inside the each
block code. You should take a look in the console for any errors.
jQuery
纯粹是一个javascript库。除ajax
,setTimeout
并setInterval
没有什么可以在异步执行JavaScript
。所以each
肯定是同步执行的。each
块代码中肯定有一些js错误。您应该在控制台中查看任何错误。
Alternatively you can take a look at jQuery queueto execute any function in the queue. This will make sure the queued function will be executed only when the previous code execution is complete.
回答by Morg.
Another reason to ask that question would be that .each will simply stop iteration when the (.each() ) function returns false, and an additional variable must be used to pass the "return false" information.
提出这个问题的另一个原因是 .each 将在 (.each() ) 函数返回 false 时简单地停止迭代,并且必须使用附加变量来传递“返回 false”信息。
var all_ok=true;
$(selector).each(function(){
if(!validate($(this))){
all_ok=false; //this tells the outside world something went wrong
return false; //this breaks the .each iterations, returning early
}
});
if(!all_ok){
alert('something went wrong');
}
回答by M Hussain
return false
in .each()
function breaks the loop only, and the remaining code outside the loop still executes. So set a flag in .each()
loop and check it outside the loop.
return false
in.each()
函数只中断循环,循环外的其余代码仍然执行。所以在.each()
循环中设置一个标志并在循环外检查它。
回答by user3027521
Same problem. So i fix like this
同样的问题。所以我像这样修复
var y = jQuery(this).find(".extra_fields");
for(var j in y)
{
if( typeof y[j] =='object')
{
var check = parseInt(jQuery(y[j]).val());
if(check==0){
jQuery(y[j]).addClass('js_warning');
mes="B?n vui lòng ch?n ??y ?? các thu?c tính cho s?n ph?m";
done=false;
eDialog.alert(mes);
return false;
}
}
}
回答by Miguel
Thats how i do it
我就是这样做的
function getAllEventsIndexFromId(id) {
var a;
$.each(allEvents, function(i, val) {
if (val.id == id) { a=i; }
});
return a;
}
回答by Tuitx
For me it works like asyncronous. If it works sync, why it works like that:
对我来说,它像异步一样工作。如果它可以同步,为什么它会这样工作:
var newArray = [];
$.each( oldArray, function (index, value){
if($.inArray(value["field"], field) === -1){
newArray.push(value["field"]);
}
}
);
//do something with newArray here doesn't work, newArray is not full yet
$.when.apply($, newArray).then(function() {
//do something with newArray works!! here is full
});
回答by Nilkamal Gotarne
I had the same issue. my $.each was inside the success function of ajax call. i made my ajax call synchronous by adding async: false
and it worked.
我遇到过同样的问题。我的 $.each 在 ajax 调用的成功函数中。我通过添加使我的 ajax 调用同步,async: false
并且它起作用了。
回答by Chris Pietschmann
The jQuery.each method loops Synchronously, but you can't guarantee that it'll loop through the items in any specific order.
jQuery.each 方法同步循环,但您不能保证它会以任何特定顺序循环遍历项目。