如何从嵌套的jQuery回调函数返回true/false
问题描述:
我正在尝试验证包含两个jQuery回调循环的javascript函数中的元素.根据条件,我想从内部jQuery循环返回true
/false
,并且应该将其发送回javascript的调用方法.如果内部循环的结果为true
,则该循环应停止运行.
I am trying to validate elements inside a javascript function which contains two jQuery callback loops. Based on the conditions I want to return true
/false
from the inner jQuery loop and that should be sent back to the calling method of javascript. If the result of the inner loop is true
the loop should stop running.
if(validate(key)){
}
else{
}
function validate(key) {
$jquery.each(function(){
$jquery.each(function(){
if(){
return true;
}
else{
return false}
})
})
}
答
我认为这就是您要寻找的东西,当满足true
条件时,这将停止两个循环
I think this is what you're looking for, this will stop both loops when the true
condition is met
function validate(key) {
var result = false;
$jquery.each(function(){
$jquery.each(function(){
if(){
result = true;
return false;//break inner loop
}
});
if(result)
return false; //break outer loop if we got true in inner
});
return result;
}
演示小提琴 满足了真实条件
Demo fiddle You can open your console and see that the loop stops when the true condition is met