$(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 新手,谢谢
最佳答案
是的,这正是 each
的工作原理。由于它实际上是一个在每次迭代中调用匿名函数的循环,因此退出这些函数也不会退出调用函数。这里返回true和false,实际上分别对应了for循环的continue
和break
。
您需要设置一个 bool 标志,然后返回 false(中断),然后在 each
之后返回 bool 标志的值
关于jQuery每个方法没有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1900172/