我有一个像这样的代码,看看是否有一些单选按钮被检查过。当我找到一组具有相同名称值的单选按钮并且没有检查过它们时,我正在使用jquery的.each函数来显示警报。当我找到一个我要发出警报并返回false时,但是在显示警报后,.each的执行会停止,但执行.each函数后的行(我的意思是执行真值)。
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
console.log('still goes here even when alert is fired');
return true;
我该如何避免这种情况?
感谢。
答案 0 :(得分:1)
您可以在更高的范围内使用相同的notAnswered
变量(或其他任何浮动您的船),如下所示:
var notAnswered;
$(":radio").each(function(){
notAnswered = $(":radio[name="+this.name+"]:checked").length == 0;
if(notAnswered){
alert("Must answer all questions");
return false;
}
});
if(notAnswered) return false;
console.log("will only fire if there's an answer");
return true;
上面的其他更改只是减少了代码,你可以减少选择引擎调用的次数:)
答案 1 :(得分:1)
var myreturnvalue = true;
$(":radio").each(function(){
var name = $(this).attr('name');
var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
var notAnswered = numAnswered == 0;
if(notAnswered){
alert("Must answer all questions");
myreturnvalue = false;
return false;
}
});
console.log('still goes here even when alert is fired');
return myreturnvalue;