使用 jQuery.each() 时返回一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3820269/
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
Return a value when using jQuery.each()?
提问by Prashant Lakhlani
I want to return false and return from function if I find first blank textbox
如果我找到第一个空白文本框,我想返回 false 并从函数返回
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :( can anybody help?
上面的代码对我不起作用:(有人可以帮忙吗?
回答by Nick Craver
You are jumping out, but from the innerloop, I would instead use a selector for your specific "no value" check, like this:
您正在跳出,但是从内部循环中,我会改为使用选择器进行特定的“无值”检查,如下所示:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return thatresult from the outer loop:
或者,在循环内部设置结果,并从外部循环返回该结果:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}
回答by T.J. Crowder
You can do it like this:
你可以这样做:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true
if you don't find it.
假设您true
没有找到它就想返回。
You may find that this is one of those sitautions where you don't want to use each
at all:
您可能会发现这是您根本不想使用的each
情况之一:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}
回答by Mr.Hunt
I want to add something to existing answers to clear the behavior of $(selector).each
and why it doesn't respect return false in OP's code.
我想在现有答案中添加一些内容,以清除$(selector).each
OP 代码中的行为以及为什么它不尊重 return false 。
return
keyword inside $(selector).each
is used to break or continue the loop. If you use return false
, it is equivalent to a break
statement inside a for/while
loop. Returning non-false is the same as a continue
statement in a for
loop; it will skip immediately to the next iteration. Source
return
关键字 inside$(selector).each
用于中断或继续循环。如果使用return false
,则相当于循环break
内的语句for/while
。返回非假与循环中的continue
语句相同for
;它将立即跳到下一次迭代。来源
Because you're returning false, the loop breaks and the function ends up returning undefined
in your case.
Your option is to use a var outside $.each
or avoid using it altogether as @TJCrowder wrote.
因为您返回 false,所以循环中断并且函数最终undefined
在您的情况下返回。您的选择是在外部使用 var$.each
或避免像@TJCrowder 所写的那样完全使用它。