Sae*_*ati 125 jquery asynchronous
考虑这种情况进行验证:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是,if块在循环完成之前执行.我期望validateForm同步执行主体,但似乎each()异步执行jQuery 函数.我对吗?为什么这不起作用?
Abr*_*ham 150
是的,jQuery each方法是同步的.几乎所有JavaScript都是同步的.唯一的例外是AJAX,计时器(setTimeout和setInterval)以及HTML5 Web Workers.
您的问题可能在您的代码中的其他位置.
提出该问题的另一个原因是,当(.each())函数返回false时,.each将仅停止迭代,并且必须使用附加变量来传递“ return 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');
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对我来说,它的工作原理就像异步的。如果它可以同步,为什么它会这样工作:
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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68009 次 |
| 最近记录: |