javascript 这个break语句在jquery/javascript中有效吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16397002/
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 this break statement valid in jquery/javascript?
提问by ACP
I have a function which selects a text based on the input string. If both matches i make it selected. PFb the function,
我有一个根据输入字符串选择文本的函数。如果两者匹配,我将其选中。PFb 函数,
function setDropdownTextContains(dropdownId,selectedValue,hfId){
$('#'+dropdownId+' option').each(function(){
if($(this).text() === selectedValue){
$(this).attr("selected", "selected");
break;
}
});
$('#'+hfId).val("ModelName doesnt match");
}
I get the below error unlabeled break must be inside loop or switch
... What am i doing wrong??
我收到以下错误unlabeled break must be inside loop or switch
...我做错了什么?
回答by VisioN
回答by flavian
A break
statement is designed to end a for, while or do-while
loop or a switch statement. It has no side effects where you are using it. What are you trying to achieve?
一个break
说法是旨在结束一个for, while or do-while
循环或switch语句。它在您使用它的地方没有副作用。你想达到什么目的?
In your specific case, just return false
在您的具体情况下,只需 return false
回答by Sudhir Bastakoti
to break you could just return false;
, like
打破你可以return false;
,就像
if($(this).text() === selectedValue){
$(this).attr("selected", "selected");
return false;
}
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop)
从 each 函数中返回 'false' 会完全停止所有元素的循环(这就像在普通循环中使用 'break' 一样)。从循环中返回“true”会跳到下一次迭代(这就像在正常循环中使用“continue”一样)
回答by drinchev
$().each
is a function method, so you will terminate it with return
$().each
是一个函数方法,所以你将终止它 return
function setDropdownTextContains(dropdownId,selectedValue,hfId){
$('#'+dropdownId+' option').each(function(){
if($(this).text() === selectedValue){
$(this).attr("selected", "selected");
return false; // <--
}
});
$('#'+hfId).val("ModelName doesnt match");
}
回答by Harish
As per jQuery documentation, break is to break out of the loop. You cannot use it inside if statement.
根据 jQuery 文档,break 是跳出循环。您不能在 if 语句中使用它。
You can use return false
instead.
你可以return false
改用。
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});