javascript html表单标签的用途是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31066693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the purpose of the html form tag
提问by D-Marc
I do not understand the purpose of the form tag in html.
我不明白 html 中表单标签的用途。
I can easily just use any input types perfectly without using the form tag. It almost seems redundant to wrap it around inputs.
我可以轻松地完美地使用任何输入类型,而无需使用表单标签。将它包裹在输入周围似乎是多余的。
Additionally, if I am using ajax to call a server-side page, I can simply use jQuery for that. The only exception is that I noticed that you have to wrap an upload script around a form tag for some reason.
此外,如果我使用 ajax 调用服务器端页面,我可以简单地使用 jQuery。唯一的例外是我注意到出于某种原因您必须将上传脚本包装在表单标签周围。
So why are forms still so widely used for simple things like text inputs? It seems like a very archaic and unnecessary thing to do.
那么为什么表单仍然如此广泛地用于简单的事情,比如文本输入?这似乎是一件非常陈旧且不必要的事情。
I just don't see the benefit or need for it. Maybe I'm missing something.
我只是没有看到它的好处或需要。也许我错过了一些东西。
采纳答案by Oka
What you are missing is an understanding of semantic markup, and the DOM.
您缺少的是对语义标记和 DOM的理解。
Realistically, you can pretty much do whatever you want with HTML5 markup, and most browsers will parse it. Last time I checked, WebKit / Blink even allows pseudo-elements inside <input>
elements, which is a clear violation of the spec - Gecko not so much. However, doing whatever you like with your markup will undoubtably invalidate it as far as semantics are concerned.
实际上,您几乎可以使用 HTML5 标记做任何您想做的事情,并且大多数浏览器都会解析它。上次我检查时,WebKit / Blink 甚至允许在元素内<input>
使用伪元素,这显然违反了规范 - Gecko 并没有那么多。然而,就语义而言,对标记做任何你喜欢做的事情无疑会使它失效。
Why do we put <input>
elements inside of <form>
elements? For the same reason we put <li>
tags inside of <ul>
and <ol>
elements - it's where they belong. It's semanticallycorrect, and helps to define the markup. Parsers, screen readers, and various software can better understand your markup when it is semantically correct - when the markup has meaning, not just structure.
为什么我们把<input>
元素放在元素里面<form>
?出于同样的原因,我们将<li>
标签放在<ul>
和<ol>
元素中 - 这是它们所属的地方。它在语义上是正确的,有助于定义标记。当标记在语义上正确时,解析器、屏幕阅读器和各种软件可以更好地理解您的标记 - 当标记具有意义,而不仅仅是结构时。
The <form>
element also allows you to define method
and action
attributes, which tell the browser what to do when the form is submitted. AJAX isn't a 100% coverage tool, and as a web developer you should be practicing graceful degradation - forms should be able to be submitted, and data transferred, even when JS is turned off.
该<form>
元素还允许您定义method
和action
属性,它们告诉浏览器在提交表单时要做什么。AJAX 不是 100% 覆盖率的工具,作为 Web 开发人员,您应该练习优雅的降级 - 即使关闭 JS,也应该能够提交表单和传输数据。
Finally, forms are all registered properly in the DOM. We can take a peek at this with JavaScript. If you open up your console on this very page, and type:
最后,表单都在 DOM 中正确注册。我们可以用 JavaScript 看一看。如果你在这个页面上打开你的控制台,然后输入:
document.forms
You'll get a nice collection of all the forms on the page. The searchbar, the comment boxes, the answer box - all proper forms. This interface can be useful for accessing information, and interacting with these elements. For example, forms can be serializedvery easily.
您将获得页面上所有表单的精美集合。搜索栏、评论框、答案框 - 所有适当的形式。此界面可用于访问信息以及与这些元素进行交互。例如,表单可以很容易地序列化。
Here's some reading material:
这里有一些阅读材料:
Note: <input>
elements can be used outside of forms, but if your intention is to submit data in any way, you should be using a form.
注意:<input>
元素可以在表单之外使用,但是如果您打算以任何方式提交数据,您应该使用表单。
This is the part of the answer where I flip the question around.
这是我翻转问题的答案的一部分。
How am I making my life harder by avoiding forms?
我如何通过避免形式让我的生活变得更艰难?
First and foremost - container elements. Who needs 'em, right?!
首先也是最重要的 - 容器元素。谁需要他们,对吧?!
Certainly your little <input>
and <button>
elements are nested insidesome kind of container element? They can't just be floating around in the middle of everything else. So if not a <form>
, then what? A <div>
? A <span>
?
当然你的小元素<input>
和<button>
元素嵌套在某种容器元素中?他们不能只是漂浮在其他一切事物的中间。那么如果不是 a <form>
,那又如何?一个<div>
?一个<span>
?
These elements haveto reside somewhere, and unless your markup is a crazy mess the container element can just be a form.
这些元素必须驻留在某处,除非你的标记是一团糟,否则容器元素可以只是一个表单。
No? Oh.
不?哦。
At this point the voices in my head are very curious as to how you create your event handlers for all these different AJAX situations. There must be a lot, if you need to cut down on your markup to save bytes. Then you must create custom functions for each AJAX event that corresponds to each 'set' of elements - which you must have to target individually or with classes, right? Theres no way to really group these elements generically, since we've established that they just kind of roam around the markup, doing whatever until they are needed.
在这一点上,我脑海中的声音非常好奇您如何为所有这些不同的 AJAX 情况创建事件处理程序。如果您需要减少标记以节省字节,则必须有很多。然后,您必须为对应于每个“元素集”的每个 AJAX 事件创建自定义函数 - 您必须单独或与类一起定位,对吗?没有办法真正对这些元素进行通用分组,因为我们已经确定它们只是在标记周围漫游,做任何事情直到需要它们。
So you custom code a few handlers.
所以你自定义了一些处理程序。
$('#searchButton').on('click', function (e) {
e.preventDefault();
var search = $('#mySearch');
$.ajax({
url: 'http://example.com/text',
type: 'GET',
dataType: 'text',
data: 'query=' + search.val(),
success: function (data) {
console.log(data);
}
});
});
$('#login').on('click', function (e) {
e.preventDefault();
var user = $('#username'),
pass = $('#password'),
rem = $('#remember');
$.ajax({
url: 'http://example.com/login',
type: 'POST',
data: user.add(pass, rem).serialize(),
dataType: 'text',
success: function (data) {
console.log(data);
}
});
});
<!-- No containers, extra markup is silly. -->
<input type="text" id="mySearch" value="query" />
<button id="searchButton">Search</button>
<input type="text" id="username" name="username" value="user" />
<input type="password" id="password" name="password" value="pass" />
<input type="checkbox" id="remember" name="remember" checked /> stay logged in
<button id="login">Login</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is the part where you say something like:
这是你说的部分:
'I totally use reusable functions though. Stop exaggerating.'
'虽然我完全使用可重用的功能。别夸大其词了。
Fair enough, but you still need to create these sets of unique elements, or target class sets, right? You still have to groupthese elements somehow.
很公平,但您仍然需要创建这些独特的元素集或目标类集,对吗?您仍然必须以某种方式对这些元素进行分组。
Lend me your eyes (or ears, if you're using a screen reader and need some assistance - good thing we could add some ARIAto all this semanticmarkup, right?), and behold the power of the generic form.
借给我你的眼睛(或耳朵,如果你正在使用屏幕阅读器并需要一些帮助——我们可以为所有这些语义标记添加一些ARIA,对吧?),看看通用形式的力量。
function genericAjaxForm (e) {
e.preventDefault();
var form = $(this);
return $.ajax({
url: form.attr('action'),
type: form.attr('method'),
dataType: form.data('type'),
data: form.serialize()
});
}
$('#login-form').on('submit', function (e) {
genericAjaxForm.call(this, e).done(function (data) {
console.log(data);
});
});
<form action="http://example.com/login" method="POST" data-type="text" id="login-form">
<input type="text" name="username" value="user" />
<input type="password" name="password" value="mypass" />
<label>
<input type="checkbox" name="remember" /> Remember me
</label>
<button type="submit">Login</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
We can use this with any common form, maintain our graceful degradation, and let the form completelydescribe how it should function. We can expand on this base functionality while keeping a genericstyle - more modular, less headaches. The JavaScript just worries about its own things, like hiding the appropriate elements, or handling any responses we get.
我们可以将它与任何常见的形式一起使用,保持我们优雅的退化,并让形式完整地描述它应该如何运作。我们可以在保持通用风格的同时扩展这个基本功能- 更模块化,更少麻烦。JavaScript 只关心它自己的事情,比如隐藏适当的元素,或者处理我们得到的任何响应。
And now you say:
现在你说:
'But I wrap my pseudo-forms in <div>
elements that have specific IDs - I can then target the inputs loosely with with .find
, and .serialize
them, and ...'
'但我将我的伪表单包装在<div>
具有特定 ID 的元素中 - 然后我可以用.find
、.serialize
它们和它们松散地定位输入......'
Oh, what's that? You actually wrap your <input>
elements in a container?
哦,那是什么?您实际上将<input>
元素包装在容器中吗?
So why isn't it a form yet?
那么为什么它还不是一种形式呢?
回答by Michael Hewson
Form tags are still necessary if you want to be able to submit the form without AJAX (which may be useful in the early stages of development). But even though it's possible to use javascript to submit data without a form tag, a few benefits still come to mind:
如果您希望能够在没有 AJAX 的情况下提交表单(这在开发的早期阶段可能很有用),则表单标记仍然是必要的。但即使可以使用 javascript 在没有表单标签的情况下提交数据,但仍然可以想到一些好处:
- Using form tags can help people read and understand you code in some cases, by showing them your intentions.
- The 'submit' method is available on forms. If you have a form with an input[type=submit], and it's not disabled, then when someone hits 'enter' while filling out one of the other form inputs, the form will submit. You can still do that by listening for the 'keydown' event on the input elements, but it's a nice bit of ui that you get for free with form tags.
- There are be a few other things that only work with a form tag, or are easier with a form tag. Developers will eventually run into these cases, and decide it's easier just to always use them everywhere and avoid problems. Really, the real question is, why notuse a form tag?
- 在某些情况下,通过向人们展示您的意图,使用表单标签可以帮助人们阅读和理解您的代码。
- “提交”方法在表单上可用。如果您有一个带有 input[type=submit] 的表单,并且它没有被禁用,那么当有人在填写其他表单输入之一时点击“输入”,表单将提交。您仍然可以通过侦听输入元素上的 'keydown' 事件来做到这一点,但这是一个很好的用户界面,您可以通过表单标签免费获得。
- 还有一些其他东西只适用于表单标签,或者使用表单标签更容易。开发人员最终会遇到这些情况,并决定始终在任何地方使用它们并避免问题更容易。真的,真正的问题是,为什么不使用表单标签?
回答by Nikola Stojanovic
I had a scenario where single web page had 3 forms, all of which had separate email fields (with different IDs). I wrapped them in separate <div>
at first. iOS auto fill on Safari behaved strangely until I wrapped all of them in <form>
tags. One of the forms had only one input field, for newsletter subscription. When user auto filled that input, web page was scrolled to next input field which was located on different part of the page.
我有一个场景,单个网页有 3 个表单,所有表单都有单独的电子邮件字段(具有不同的 ID)。一开始我把它们分开包装<div>
。Safari 上的 iOS 自动填充行为很奇怪,直到我将它们全部包裹在<form>
标签中。其中一个表单只有一个输入字段,用于订阅新闻通讯。当用户自动填写该输入时,网页将滚动到位于页面不同部分的下一个输入字段。
So, thanks Oka for long post. Tags with semantic meaning should be used whenever possible, because you never know which browser/device doesn't handle other solutions well.
所以,感谢 Oka 的长篇文章。应尽可能使用具有语义含义的标签,因为您永远不知道哪个浏览器/设备不能很好地处理其他解决方案。
回答by Rohit Azad
The HTML element represents a document section that contains interactive controls to submit information to a web server.
HTML 元素表示一个文档部分,其中包含用于向 Web 服务器提交信息的交互式控件。
We are all familiar with forms on html web pages. For many different reasons people or companies are asking for our e-mail addresses, names and site URLs. Buying products on the Internet today is mostly a breeze and with the advent of security devices, the method used for submitting your details and hard earned money is usually performed via forms.
我们都熟悉 html 网页上的表单。出于许多不同的原因,人们或公司要求我们提供电子邮件地址、名称和站点 URL。如今在 Internet 上购买产品几乎是轻而易举的事,随着安全设备的出现,用于提交您的详细信息和辛苦赚来的钱的方法通常是通过表格执行的。
more info
更多信息