当我在嵌套的each()函数中返回false时,如何停止使用submit()提交表单?
我需要在提交之前检查表单,但需要循环执行一些输入。如果输入无效,我需要返回 false 并停止提交,但是因为测试是在嵌套的each()函数内,所以它不会在外部submit()函数中返回false:
$("#my_form").submit(function() { $("#my_form .my_text_inputs").each(function() { if ($(this).val() == "bad value") { alert("Input was invalid"); return false; } }); return true; });
我的解决方案是:
$("#my_form").submit(function() { var _bSubmitTheForm = true; $("#my_form .my_text_inputs").each(function() { if ($(this).val() == "bad value") { alert("Input was invalid"); _bSubmitTheForm = false; return false; } }); return _bSubmitTheForm; });
...是否有一个更优雅的方式来做到这一点?
谢谢
I need to check a form before submitting but need to loop through some inputs. If an input is invalid, I need to return false and stop the submit, however because the test is within the nested each() function it's not returning false in the outer submit() function:
$("#my_form").submit(function() { $("#my_form .my_text_inputs").each(function() { if ($(this).val() == "bad value") { alert("Input was invalid"); return false; } }); return true; });
My solution is:
$("#my_form").submit(function() { var _bSubmitTheForm = true; $("#my_form .my_text_inputs").each(function() { if ($(this).val() == "bad value") { alert("Input was invalid"); _bSubmitTheForm = false; return false; } }); return _bSubmitTheForm; });
...is there a more elegant way to do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$.each
中的return false
将跳出each 循环。所以你还是想返回那里进行优化。除此之外,我建议使用 jQuery validate 来实现相同的结果。
return false
from within the$.each
will break out of the each loop. So you still want to return there for optimization.Besides that, I would recommend using jQuery validate to achieve this same result.