本文共 3030 字,大约阅读时间需要 10 分钟。
Forms are an extremely important part of HTML and the Web Platform. They allow users can interact with the page and
表单是HTML和Web平台的极其重要的组成部分。 它们使用户可以与页面进行交互,并且
and much much more.
还有更多。
By default, forms submit their content to a server-side endpoint, which by default is the page URL itself:
默认情况下,表单将其内容提交到服务器端端点,默认情况下是页面URL本身:
We can override this behavior by setting the action
attribute of the form element, using the HTML method defined by the method
attribute, which defaults to GET
:
我们可以使用method
属性定义HTML方法(默认为GET
通过设置form元素的action
属性来覆盖此行为:
Upon clicking the submit input element, the browser makes a POST request to the /contact
URL on the same origin (protocol, domain and port).
单击提交输入元素后,浏览器对来自相同来源(协议,域和端口)的/contact
URL发出POST请求。
Using JavaScript we can intercept this event, submit the form asynchronously (with and ), and we can also react to events happening on individual form elements.
使用JavaScript,我们可以拦截此事件,异步提交表单(使用和 ),我们还可以对单个表单元素上发生的事件做出React。
I just described the default behavior of forms, without JavaScript.
我只是描述了没有JavaScript的表单的默认行为。
In order to start working with forms with JavaScript you need to intercept the submit
event on the form element:
为了开始使用JavaScript处理表单,您需要拦截form元素上的submit
事件:
const form = document.querySelector('form')form.addEventListener('submit', event => { // submit event detected})
Now inside the submit event handler function we call the event.preventDefault()
method to prevent the default behavior and avoid a form submit to reload the page:
现在在event.preventDefault()
事件处理函数中,我们调用event.preventDefault()
方法来防止默认行为并避免提交表单重新加载页面:
const form = document.querySelector('form')form.addEventListener('submit', event => { // submit event detected event.preventDefault()})
At this point clicking the submit event button in the form will not do anything, except giving us the control.
此时,单击表单中的“提交事件”按钮将不会执行任何操作,除非给我们控件。
We have a number of events we can listen for in form elements
我们可以在表单元素中收听许多事件
input
fired on form elements when the element value is changed
更改元素值时在表单元素上触发input
change
fired on form elements when the element value is changed. In the case of text input
elements and textarea
, it’s fired only once when the element loses focus (not for every single character typed)
change
元素值时在表单元素上触发的更改。 对于文本input
元素和textarea
,当元素失去焦点时,它仅被触发一次(并非针对键入的每个字符)
cut
fired when the user cuts text from the form element
cut
解雇当用户从表单元素剪切文本
copy
fired when the user copies text from the form element
copy
发射时从表单元素用户复制文本
paste
fired when the user pastes text into the form element
paste
当用户将文本粘贴到表单元素解雇
focus
fired when the form element gains focus
focus
发射时的表单元素获得焦点
blur
fired when the form element loses focus
当表单元素失去焦点时触发blur
Here’s a sample form demo on Codepen:
这是Codepen上的示例表单演示:
See the Pen by Flavio Copes () on .
见笔由弗拉维奥·科佩斯( 上) 。
翻译自:
转载地址:http://bvqgb.baihongyu.com/