如何在JavaScript中收听表格提交事件?
我想编写自己的表单验证JavaScript库,并且我一直在寻找Google如何检测是否单击提交按钮,但我发现的只是您必须在其中使用onclick On onsubmit =“ function()” < /代码>在HTML中。
我想制作此JavaScript,这样我就不必触摸任何HTML代码,例如添加OnSubmit或OnClick JavaScript。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么人们在不需要时总是使用jQuery?
人们为什么不能只使用简单的JavaScript?
回调
是在提交表单时要调用的函数。关于
eventTarget.AddeventListener
,查看。要取消本机
提交
事件(防止表格被提交),请使用.preventdefault()
在您的回调功能中,收听
提交
带有库的事件,如果由于某种原因决定了一个库(您已经在使用一个库,或者您不想处理跨浏览器问题)在普通库中收听提交事件的方法:
jQuery
其中
ele
是表单元素参考,callback
是回调函数参考。 参考angularjs(1.x)
非常简单,其中
$ scope
是“ noreferrer”>控制器。 参考eack
只需将处理程序传递到
onsubmit
prop。 参考其他框架/libraries
请参阅您的框架文档。
验证
您可以随时在JavaScript中进行验证,但是使用HTML5,我们也具有本机验证。
您甚至不需要任何JavaScript!每当不支持本机验证时,您都可以退缩到JavaScript验证器。
演示:
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
callback
is a function that you want to call when the form is being submitted.About
EventTarget.addEventListener
, check out this documentation on MDN.To cancel the native
submit
event (prevent the form from being submitted), use.preventDefault()
in your callback function,Listening to the
submit
event with librariesIf for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:
jQuery
Where
ele
is the form element reference, andcallback
being the callback function reference. ReferenceAngularJS (1.x)
Very straightforward, where
$scope
is the scope provided by the framework inside your controller. ReferenceReact
Simply pass in a handler to the
onSubmit
prop. ReferenceOther frameworks/libraries
Refer to the documentation of your framework.
Validation
You can always do your validation in JavaScript, but with HTML5 we also have native validation.
You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.
Demo: http://jsfiddle.net/DerekL/L23wmo1L/
这是当发生
OnSubmit
时,可以使用自己的JavaScript函数的最简单方法。html
javaScript
This is the simplest way you can have your own javascript function be called when an
onSubmit
occurs.HTML
JavaScript
根据您的要求,您也可以在没有诸如jQuery之类的图书馆的情况下进行以下操作:
将其添加到您的头上:
您的表格可能仍然看起来像:
Based on your requirements you can also do the following without libraries like jQuery:
Add this to your head:
And your form may still look something like:
如果您在同一页面中有多个表格&amp;您想处理提交事件听众而不使用ID
jQuery
纯JavaScript Trick
我希望这对某人有帮助
If you have multiple forms in same page & you wants to handle submit event Listener without using Id
jQuery
Pure JavaScript trick
I hope this helps to someone
与jQuery:
With jQuery: