jQuery每个方法不返回值 [英] jQuery each method does not return value
问题描述
$(document).ready(function() {
$('#commentForm').submit(function(){
return $('input[type=text], textarea').each(function(index){
if($(this).attr('value') == ""){
alert(msgHash[$(this).attr('id')]);
return false;
}else{
if(!$(this).attr('value').match(validateHash[$(this).attr('id')])){
//Do nothing
alert(msgOnError[$(this).attr('id')]);
return false;
}
}
});
return true;
});
});
这里是msgOnError,msgHash和msgHash的映射,我用来获取具有特定ID的每个文本框的消息 不幸的是,每种方法都不会返回false来取消提交表单.我究竟做错了什么 ??我是jQuery新手,谢谢
Here msgOnError, msgHash and msgHash are map that I use to get messages for each text box with particular ID Unfortunately each method does not return false to cancel submission of the form. What am I doing wrong ?? I am new to jQuery, Thanks
推荐答案
是的,这正是each
的工作方式.由于实际上是在每次迭代中调用匿名函数的循环,因此退出这些函数也不会退出调用函数.在这里,返回true和false分别对应于for循环的continue
和break
.
Yes, that's exactly how each
works. Since it's actually a loop that calls your anonymous function in each iteration, exiting those functions, will not exit the calling function as well. Returning true and false here, is actually corresponding to the continue
and break
of the for loop, repsectively.
您需要设置一个布尔标志,然后返回false(中断),然后在each
You're gonna need to set a boolean flag, then return false (break), and then return the value of your boolean flag after the each
这篇关于jQuery每个方法不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!